Posts Tagged ‘CSS’

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.

Stacking the Deck

Sunday, May 23rd, 2010

Managing styles can be frustrating. Most people just stuff everything into one stylesheet. This works for smaller sites really well, but it doesn’t scale to larger sites. The stylesheet gets so large that it’s difficult to know what is going to override what. You end up relying in tools like Firebug to find out how adding a new style is going to affect the site.

She’s a brick house

You can’t really get rid of that global stylesheet because defining styles that apply to the whole site incredibly useful. You don’t want have the same styles duplicated across multiple stylesheets. That causes bloat. It makes updating the styles difficult too, but it would be great to have page level granularity. So when the creative department comes down on you like a ton of bricks, you can change the blue to gold in a flash. (actually it was more of a amber-canary with a splash of wheat).

The trick is to do both. Start with a global stylesheet and define the most commonly used styles. Use good defaults: define all your font families and sizes; create classes for all of your sprites; and create all of the utility classes for floating and clearing elements. This will be the foundation for all of your future work.

Then create a set mid-level of stylesheets. You would include this one immediately after your global sheet. One for each section of your site. These stylesheets will be your work horses. This is where you setup your layout fundamentals for section.

And finally

On the pages that need it. Create page specific stylesheets. Included after your section stylesheet. So, now, when the client says that they actually liked the blue better. It’s now a 5 second change.