csscalc

Use max-content in calc


Imagine I have a <div> with some <p> in it:

#myDiv {
  width: max-content;
  border-style: dashed;
}
<div id="myDiv">
    <p>This is my text</p>
</div>

But I don't like the fact that the text is so close to the border, so I tried this:

#myDiv {
  width: calc(max-content + 2px);
  border-style: dashed;
}
<div id="myDiv">
  <p>This is my text</p>
</div>

But (as you can see) it didn't work.


So my question is if there's a way to create a <div> with a width of

Two pixels more than the content in it

since what I tried

calc(max-content + 2px)

didn't work.

Thank you in advance.


Solution

  • Unfortunately you can't use the max-content keyword with calc()

    My solution to your problem would be to use padding:

    #myDiv {
      width: max-content;
      padding-inline: 2px;
      border-style: dashed;
    }
    <div id="myDiv">
      <p>This is my text</p>
    </div>