CSS / THEMING THURSDAYS

Box Sizing: Padding without the Math!

Have you ever had to lay out a container div then needed to add padding? Then to get the correct width you had to subtract the amount of padding to the width? Well not anymore!

Box sizing is a CSS rule that allows you to fix the width and when you add padding, it doesn’t affect the width! It has two settings: content-box, which is the default, and border-box.

Here’s a diagram of how the two box-sizing settings work.

Box Sizing: Paddings without the math!

Box Sizing: Paddings without the math!

An Example

You have a 200px by 120px div and you want to add 20px of padding and a 5px border to it. If you just do:

mydiv {
padding: 20px;
border: 5px solid black;
width: 200px;
height: 120px;
}

You get a 250px by 170px container. So normally what we do is:

mydiv {
padding: 20px;
border: 5px solid black;
width: 150px;
height: 70px;
}

But who has time to do math? Especially if your padding and borders are not cleanly set for some reason:

mydiv {
padding: 1px 24px 15px 19px;
border-top: 1px solid black;
border-right: 20px solid black;
border-bottom: 17px solid black;
border-left: 32px solid black;
width: ???MATH!!;
height: ???MATH!!;
}

This is the default behaviour of the box-sizing rule which is by default set to content-box.

So what you do is add the rule box-sizing:border-box;:

mydiv {
padding: 1px 24px 15px 19px;
border-top: 1px solid black;
border-right: 20px solid black;
border-bottom: 17px solid black;
border-left: 32px solid black;
box-sizing:border-box;
width: 200px; /*Ahh, no math.*/
height: 170px; /*Ahh, no math.*/
}

So I’m not saying math is bad. But if there’s a way to automate things, then why not?

Ok so this isn’t really specific to Drupal. But I thought to feature a few CSS tricks that are, well, relatively not widely known.

References and Further Reading:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s