Posts Tagged ‘box-model’

Why width: 100% doesn’t do what you think it does

Sunday, June 13th, 2010

Something I run across every so often when fixing bugs is a problem of content overflowing its parent element. The child has padding, margins, or a border, and a width set to 100%. This seems like it should fill the available space, but it protrudes out instead.

The weird behavior comes from the standard box model. According to the standard box model, when you set the width, it sets the width of the content area. The padding, border, and margin get wrapped around it. Meaning that the box, which is already the full width of it’s parent, gets pushed out beyond the edge.

The fix is painfully simple. Simply set width of the chid element to auto, or remove it entirely. Block level elements automatically fill the available space, and that calculation takes into account the borders, margin, and padding.