Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add padding or border to a DIV and keep width and height?

Tags:

css

Is there some way to keep a set width/height for a DIV, and pad the content without the DIV growing? See example below. I want all the boxes to be exactly 140x140.

HTML:

<div class="box1">Howdy.</div>
<div class="box2">Howdy.</div>
<div class="box3">Howdy.</div>​

CSS:

.box1 {
    width: 140px;
    height: 140px;
    background: #f66;
}

.box2 {
    width: 140px;
    height: 140px;
    background: #66f;
    padding: 1em;
}

.box3 {
    width: 140px;
    height: 140px;
    background: #6f6;
    border: 1em solid #000;
}

Fiddle: http://jsfiddle.net/Wrc5S/

like image 676
CaptSaltyJack Avatar asked Mar 12 '12 22:03

CaptSaltyJack


2 Answers

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.

like image 22
Remote Avatar answered Sep 27 '22 17:09

Remote


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

like image 59
Dampsquid Avatar answered Sep 27 '22 17:09

Dampsquid