htmlcssbox-sizing

Div width percentage not working in CSS


Here is my CSS:

.leftdiv {
    width:20%;
    border:2px solid blue;
    float:left;
}

.middlediv {
    width:60%;
    border:1px solid orange;
    float:left;
}

.rightdiv {
    width:20%;
    border:1px solid black;
    float:right;
}

Here is my html:

<body>
    <div class="leftdiv">left</div>
    <div class="middlediv">middle</div>
    <div class="rightdiv">right</div>
</body>

What I expect to see is three divs across the screen taking up 100% of the screen width.

Instead see this:

enter image description here

The right div is on the next line.


Solution

  • This is because of the borders. If you leave out the borders your div will align. Using the border-box solves the problem:

     .leftdiv{
    box-sizing: border-box; 
    width:20%;
    border:2px solid blue;
    float:left;}
    
    .middlediv{
    box-sizing: border-box;
    width:60%;
    border:1px solid orange;
    float:left;}
    
    .rightdiv{
    box-sizing: border-box;
    width:20%;
    border:1px solid black;
    float:right;}
    

    The idea of a box-sizing: border box is that it modfies the behaviour of the normal box model to treat the padding and border as a part of the width element. So now when you set the % width the border is already taken into account. This is why now the 20+20+60 amount to 100%.

    Additional info can be found in this link