How to add padding or border to a DIV and keep width and height?
The cleanest method would probably be to nest <div>
tags within your current <div>
tags, and apply the padding to them:
<div class="box" id="box1"><div>Howdy.</div></div>
<div class="box" id="box2"><div>Howdy.</div></div>
<div class="box" id="box3"><div>Howdy.</div></div>
CSS:
.div { /* ... */ }
.div > div { padding: 1em; } /* Apply to all inner divs */
#box2 > div { padding: 1em; } /* Only apply to the inner div in #box2 */
Depending on what browsers you need to support, you could change the box-sizing attribute on these DIVs to be border-box. That will allow you to set a height and a width on each box, without the padding or borders effecting the dimensions you set.
It has been suggested by a few people to set this globally for all elements in a reset because it makes things a lot easier to style (and is arguably a better box-sizing model than the default). To do this, you would use something like:
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
More information, including browser support and some general warnings can be found here: http://paulirish.com/2012/box-sizing-border-box-ftw/
Yes just subtract twice the padding or border from the height and width. In other words, subtract the padding or border from each side of the div
:
.box1
{
width: 140px;
height: 140px;
background: #f66;
}
.box2
{
width: 130px;
height: 130px;
background: #66f;
padding: 5px;
}
.box3
{
width: 130px;
height: 130px;
background: #6f6;
border: 5px solid #000;
}
fiddle example: http://jsfiddle.net/N6BYH/
Or use box-sizing: border-box;
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing.
Yes you can use
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
to change the box model to make borders and padding internal to your width/height, but margins are still added.
and your updated Fiddle
more information here css tricks