Evan Chen

Founder at Taurus

Contact me: hello@evan.lc, @ebzlo
December 2, 2012
A neat CSS trick

I apologize for the title, but I really couldn’t think of a better name for this post. I’m also making a fairly big gamble that I will never discover another CSS trick again worth writing about.

Anyway, I just wanted to share a tag I just had the pleasure of meeting. But before I introduce you, please take note of the following examples.

What’s going on here?

While example A is simply expected behavior, example B might throw some new designers for a loop. As we all eventually come to realize, an HTML element’s width is exclusive of it’s padding, border, and margin. By setting an element to 100% and a padding of 5px (example B), you actually set the element to take up 5 pixels + 100% + 5 pixels worth of space.

The goal here is to create a padded element that fits snugly into its parent (example C). You could set the padding to use a small percentage and just appropriately deduct that from the width, but that lacks consistency at extreme resolutions and feels like “hacky” responsive design.

Okay, okay, so how do I do it?

Set the element’s box-sizing to “border-box”. This CSS tag forces the browser render the width inclusive of the padding and border. The final CSS for example C ends up being as follows:

width: 100%;
padding: 5px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;

Neat. :)

2 notes