I'm not a designer. When writing CSS it often happens that I need to add some padding to an element. How do you avoid that padding to propagate to the parent element ?
HTML:
<div id="outer">
<input id="login">
</div>
CSS:
#outer {
width: 300px;
}
#login {
width: 100%;
padding: 1em;
}
If you use that HTML+CSS, you'll see that the #outer
element is bigger than 300px
. The easiest solution if to re-write the #login
's width
to "300px - to_pixel(1em)"
. It works well but also means that now the font size needs to be fixed. Is there another way where I don't need to convert everything in pixels ?
To avoid the width or height getting increased or decreased when using CSS properties like margin , padding , etc, we can use the CSS property called box-sizing and set its value to border-box on the element in CSS.
If an element has a specified width, any padding added to that element will add to the total width of the element. This is often an undesirable result, as it requires that an element's width be recalculated each time the padding is adjusted.
Now, because of the way the box sizing works in CSS, adding the padding to your element will add to its dimensions, since the width of the padding area will be added to the width of the content area, and so the total width (and height) of the element will increase.
An element's padding area is the space between its content and its border. Note: Padding creates extra space within an element. In contrast, margin creates extra space around an element.
You can css box-sizing
property like this:
#outer {
width: 300px;
background:red;
height:100px;
}
#login {
width: 100%;
padding: 1em;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
box-sizing:border-box;
}
box-sizing
does not work in IE7
What you want is the box-sizing property. Take a look at this jsFiddle for it in practice. Just add this:
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
to your #login
CSS. This is supported in most modern browsers, including IE8+.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With