Nothing is for sale here. Freewill tips keep the site running. Want to help? → Tip via Paypal
CSS Box Sizing
Take a look at the four boxes below. They’re were all coded to the same width and height, but obviously they are not displayed at the same size.
Box 1 is shown correctly at the coded size of 100×100 pixels, although this website is responsive so it may not be that exact size, depending on your device. The point will remain true, however, because all the boxes will be effected equally. The others are larger because CSS padding and/or a border is used.
You see, adding a CSS border or padding increases the size of the box. That’s not the way most folks expect it to work. It’s flummoxed a lot of webmasters.
Box 2 has a 12 pixel border added to it. You can see how the box is no longer displayed at the size it was coded. Instead of being 100×100, it’s now 124×124 because of the border (12 pixels on each side).
Box 3 has 24 pixels of padding, so its size increased to 148×148 because of the padding.
Box 4 has a 12 pixel border and 24 pixels of padding so its size has increased to 172×172 because of the border and padding.
So, without the box-sizing property (discussion coming up), the width of an element is really: width + padding + border. Same goes for the height, just substitue height for width in that equation.
Now let’s take a look at the same boxes with just one change, the box-sizing property has been added.
Now the boxes are all the same size. You can see how the text inside the boxes has shifted according to the CSS properties used with each box.
Here’s the CSS that was added:
box-sizing: border-box;
In addition to the “border-box” value for the box-sizing property, there are a few more options. I’ve listed them below and explained what they do.
- Value: content-box
- This is the default style. The width and height properties define the content area, while the padding, border and margin are added on the outside of the box. This is what you see in the “before” examples and is the reason all the box examples appear to be a different size even though the width and height are the same for each box.
- Value: padding-box
- The width and height properties include the padding size, and do not include the border or margin.
- Value: border-box
- The width and height properties include the padding and border, but not the margin. Note that the margin is measured outside of the box in all box-size values. The purpose of the margin is to provide space around an element.
There you go, a dandy tutorial all boxed up for you.