cssmaintainabilitycode-maintainability

CSS child width 100% or px question


Maybe a simple question with an easy answer.

I wondered today what is the difference between a child width in px or 100%, when the child is going to be the exact same width as the parent. The outcomes will be the same I know, but what is best to use?

Example;

div {width: 300px;}
h1 {width: 300px;} /*or..*/
h1 {width: 100%;}

<div>
<h1>Width of child</h1>
</div>

Does it matter? And which do you use?


Solution

  • Visually, both of your examples will look the same.

    But using width: 100% for the child element means if you ever want to change the width of both, you only need to change the width of the parent element.

    Also note that a h* tags are block-level elements, so, by default, it's already set to 100% width, so in your example, setting any width for h1 is redundant.