'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 1:[1]

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>

Solution 2:[2]

You can set the div to behave like an inline-block element and add padding: 2px to it. I think it would work the same way as you want. So, here's the code:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sfili_81