How can I add padding to an element without adding on top of the predefined width?
It's good to define the width of a column to make a clean grid for the layout; but also wants to add padding to the contents inside the column. Any way to specify that?
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.
Normally, when an element's size is set, the width and height properties determine the width and height of the element's content box. Any padding added to the element will increase the total computed width and/or height of the element—this is how the default box model works in regards to sizing the element.
The width and height properties include the content, but does not include the padding, border, or margin.
Padding and Element Width The content area is the portion inside the padding, border, and margin of an element (the box model). So, if an element has a specified width, the padding added to that element will be added to the total width of the element.
element {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
Use box-sizing, it makes padding inclusive: https://developer.mozilla.org/en-US/docs/CSS/box-sizing
Example:
div {
box-sizing:border-box;
-moz-box-sizing:border-box; /* Firefox */
-webkit-box-sizing:border-box; /* Safari */
}
It's worth noting that this won't work on IE7.
For IE8, please see the top answer to this Q: box-sizing: border-box => for IE8?
Everytime you add padding to block element, the width of this element changes. This problem has many solutions. I usually set margin
to first child element and set width: 100%
for this element.
For example, we have:
<div id="main">
<div id="child">
This is content with margin
</div>
</div>
CSS style for these elements:
#main {
border: solid 1px red;
float: left;
width: 5em;
}
#child {
border: solid 1px blue;
float: left;
width: 100%;
margin: 0.5em;
}
This is a solution for any browser
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