Home > Enterprise >  Use max-content in calc
Use max-content in calc

Time:04-14

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.

CodePudding user response:

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>

CodePudding user response:

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>

  • Related