The question embedded in the title of this post is really only one of may possible questions the solution below addresses. For instance:
- Why is my block level html element that is styled with
width:200px;wider than 200 pixels?
- How can I prevent my block level element from changing it’s dimensions when I change it’s padding style property?
- <Insert your mysterious-resizing block level element question here>.
I added the Twitter Facebook Google Plus One Social Share plugin to this site today (so like me, please — I’m lonely in my little corner of the Internet). I like the plugin so far, but a small issue occurred when I set the plugin’s location to “Above and below the post” — the rendered container was missing it’s right border:
So how do I fix this?
Set the div’s
box-sizing CSS attribute to
The two boxes (divs) below have the same width, height and padding, yet one is larger than the other. Why?
Both divs above have their style widths and heights set to 200px. However, I’ve applied a 10px vertical and 30px horizontal padding property to each div. The reason the second div remains at 200px x 200px regardless of the padding is that I’ve added the box-sizing: border-box; style property, which tells the browser (well, most browsers) the padding should be applied from the outer part of the box inward, thereby leaving the height and width intact. Here are the boxes again and the corresponding code:[crayon-5c97cab38a8a3400779231/] [crayon-5c97cab38a8ac893484012/]
Bingo! Check out the FB/Google/etc. button’s container at the top and bottom of this post (assuming I am still using the plugin when you read this). You can now see the right border intact! The exact style I used is this:[crayon-5c97cab38a8af586539271/]
- There is an old jQuery bug that removes padding and border-width on an element when this attribute/property is set. It appears to have been fixed in v.1.8.
- The box-sizing style attribute is not yet an official CSS standard (W3C draft here). As such, it may not work in all browsers. Here is a compatibility list from caniuse.com.
- Add the -moz- and -webkit- prefixes if you are concerned with any version of Firefox and earlier versions of Safari, and Opera.