Home > database >  Can I use the CSS width property on text (eg. h1, p)?
Can I use the CSS width property on text (eg. h1, p)?

Time:11-09

I have always avoided using the CSS width property (including max-width / min-width) on text elements, such as h1, h2, h3, p etc. Instead, I will set widths on containing, block level elements (such as a div).

However, I do this out of intuition or something I once learned, but I can't find any specification as to whether this is correct or not. Am I just making this up, or is there some kind of CSS/HTML specification that lays this out?

Or, am I just confusing h1 etc with inline elements (eg. span), where width has no effect?

Can I do this:

<style>
.custom-class {
  width: 500px;
}
</style>

<h1 class="custom-class">Test</h1>

Or should I do this?

<style>
.custom-class {
  width: 500px;
}
</style>

<div class="custom-class">
  <h1>Test</h1>
</div>

CodePudding user response:

I assume you are confusing it with inline elements. I don't see a general problem with something like this:

h1 {
   background-color: orange;
   width: 400px;
   margin: 0 auto;
   text-align: center;
}

CodePudding user response:

MDN is usually a reliable reference and it says the CSS width property:

Applies to all elements but non-replaced inline elements, table rows, and row groups

See https://developer.mozilla.org/en-US/docs/Web/CSS/width

There is some interesting, if slightly out of date in some areas, discussion of the meaning of non-replaced inline elements at: https://stackoverflow.com/questions/12468176/what-is-a-non-replaced-inline-element#:~:text=A non-replaced element is simply an element that,CSS. The concept has somewhat changed over time.

And I think the quote from MDN would be a little clearer if the 'but' was 'except'. So we could say for example that:

width works on all elements except non-replaced inline elements for example span.

  • Related