rdmueller
rdmueller

Reputation: 11012

Div border problem

I am sure that this question is already answered, but I find it hard to search for it.

I have the following html:

<div id='outerBox'>
  <div id='leftBox'><div id='secondLevelBox'></div></div>
  <div id='rightBox'></div>
</div>

and the following css:

#outerBox {
    width: 300px;
    height: 200px;
    border: 1px solid black;
}
#leftBox {
    height: 100%;
    width: 55%;
    background-color: blue;
    float: left;
}
#rightBox {
    height: 100%;
    width: 45%;
    background-color: yellow;
    float: left;
}
#secondLevelBox {
    height: 100%;
    width: 100%;
}

(See http://jsfiddle.net/dsMdb/1/)

this displays ok. But if I now add a border: 1px solid red to one of the inner divs, they will grow 2 pixels and the layout will break: http://jsfiddle.net/dsMdb/5/

How can I wrokaround this? (solutions for IE >=8 and current FF are ok)

Upvotes: 1

Views: 2218

Answers (3)

Noel Frostpaw
Noel Frostpaw

Reputation: 3999

You can change the way the browser is supposed to calculate the offset for the border & layout. Take a look at the Box Model properties in CSS3, this way you can define the offset etc.

The command you're looking for in CSS is box-sizing. By default this set to content-box, which adds the width, padding etc as different values on top of each other.

By setting it to border-box, you can force the browser to instead render the box with the specified width and height, and add the border and padding inside the box. Should apply to your border as well normally.

Upvotes: 1

indianwebdevil
indianwebdevil

Reputation: 5127

I would suggest to have pixel graduation in the width and accordingly give room for border, like

Since total width is 300 px,

#leftBox {
    height: 100%;
    width: 165px;
    background-color: blue;
    float: left;
}
#rightBox {
    height: 100%;
    width: 145px;
    background-color: yellow;
    float: left;
}

now reduce the width accordingly and this would work across browsers.

Upvotes: 1

Kalle H. V&#228;ravas
Kalle H. V&#228;ravas

Reputation: 3615

Problem is that it adds a border on the outside of that inner div. Since your red border is 1px, then it adds total of 2px.

Quick way to fix this is to remove `2px` from the outer `div`s width.

#outerBox {
    width: 298px;
    height: 200px;
    border: 1px solid black;
}

Also, I would like to add, that this fix is very browser compatible ;)

Upvotes: 1

Related Questions