The difference between width: auto; and width: 100%;

My friend Scotty asked me to help him debug a CSS issue he had with his grid generator which was caused by him defining width: 100%;.

It’s almost never a good idea to define width: 100%;. The property is misleading in that it seem like you’re defining the element’s visual size. However, you’re actually making a huge change to its behavior.

By default, block level elements fill the entire width of the parent container because of width: auto;.

width: auto; stretches to the full width and subtracts margins, padding, or borders from the available space inside.

width: 100%; forces the element to become as wide as the parent and will add additional spacing to the width of the element. This typically causes problems.

In the example below, the black border represents the parent container. The blue and green boxes are child nodes that have a border: 20px solid red;.

The difference is that the blue box has width: auto; while the green box has width: 100%;.

See the Pen H2F - March 25, 2014 #1 by Ian Jennings (@ianjennings) on CodePen.

See how the extra space from the border: 20px solid red; makes the green box bleed out of the parent container? This is because the green box has width: 100% and the borders are being added to the width rather than subtracted.

The same is true for padding and margins, let’s take a look.

See the Pen H2F - March 25, 2014 #2 by Ian Jennings (@ianjennings) on CodePen.

See how width: auto; doesn’t bleed out of the border no matter what extra spacing properties are defined?

Some CSS properties like width define behaviors that instruct the browser to render the object with an entirely different formula. Similar culprits are display and position, which I’ll cover in the future.

It’s worth noting that it is possible to use width: 100%; with both borders and padding and not have the element grow in size. You can learn how in my follow up post about the modern box-sizing: border-box;

CSS and HTML typically work out of the box. The solution to many issues is usually not to write more CSS, but to remove problematic CSS. It’s important to learn what side effects CSS properties like width have.

And that’s exactly what I’m going to help you do. Stay updated by subscribing to the newsletter and following me on twitter.