Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add borders to div without messing up the layout?

I have the following elements:

<body>
    <div id="container">
        <div id="sidebar1"></div>
        <div id="content">
            <h3>Lorem ipsum</h3> 
            <p>Whatnot.</p>
        </div>
        <div id="sidebar2"></div>
    </div>
</body>

Following this style:

/* ~~ this fixed width container surrounds all other divs~~ */
 #container {
    width: 960px;
    background-color: #FFF;
    margin: 0 auto;
    overflow: hidden;
}
#sidebar1 {
    float: left;
    width: 180px;
    /*border: 2px solid black;*/
    background-color: #EADCAE;
    padding: 0px 0px 100% 0px;
}
#content {
    padding: 10px 0;
    width: 600px;
    float: left;
}
#sidebar2 {
    float: left;
    width: 180px;
    /*border: 2px solid black;*/
    background-color: #EADCAE;
    padding: 0px 0px 100% 0px;
}

I am trying to achieve this layout: http://jsfiddle.net/QnRe4/

But as soon as I un-comment the borders it turns into this: http://jsfiddle.net/FZxPQ/

** Solved **

The border width was added to each element's total width making them too wide to fit in the container. Removing 2x the border width from each column's width solves the problem: http://jsfiddle.net/FZxPQ/4/

like image 439
Pi_ Avatar asked May 24 '13 13:05

Pi_


2 Answers

CSS box-sizing to the rescue! This property

alters the default CSS box model used to calculate widths and heights of elements

The border-box value means that

the width and height properties include the padding and border

/* support Firefox, WebKit, Opera and IE8+ */
#container, #sidebar1, #sidebar2 {
         box-sizing: border-box;
    -moz-box-sizing: border-box;
}

However, browser support is not 100% standardized.

As other answers have already mentioned the extra width which pushes the sidebars out of alignment is because the width calculation includes the border width. box-sizing simply tells the browser that an element with a given width/height should include any border and padding values into the final width/height calculations.

like image 78
andyb Avatar answered Oct 20 '22 02:10

andyb


The problem is that when you add in the boarder, the size of the outer divs increased by 4, 2px on each size. So, your container needs to grow in size by 8px.

So change your container to:

 #container {
    width: 970px;
    background-color: #FFF;
    margin: 0 auto;
    overflow: hidden;
}

See: http://jsfiddle.net/QnRe4/13/

like image 35
Tyanna Avatar answered Oct 20 '22 01:10

Tyanna