0

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.

kukkuz
  • 41,512
  • 6
  • 59
  • 95
Ray
  • 21
  • 1
  • 3

4 Answers4

2

The issue is that padding and border are, by default, calculated in addition to the width, not included in the width value. You need to use the box-sizing: border-box override to have them included:

div { box-sizing: border-box; }

Or, preferable, add it to each individual div's style block (because you might not want to blanket apply it to all divs on the page).

.leftdiv,.middlediv,.rightdiv{
  box-sizing: border-box;
}

Example: https://codepen.io/anon/pen/RLZWWO

delinear
  • 2,745
  • 1
  • 10
  • 21
2

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

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
1

The border takes up additional space that is not accounted for in the div width. Try adding box-sizing: border-box; to each of your div classes.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36
1

You should add this:

html, body {
  margin: 0;
}

to reset the default margin of the all-wrapping body and html element to zero

and

* {
  box.sizing: border-box;
}

to include padding and borders in your percentage values.

html,
body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.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;
}
<body>
  <div class="leftdiv">left</div>
  <div class="middlediv">middle</div>
  <div class="rightdiv">right</div>
</body>
Johannes
  • 64,305
  • 18
  • 73
  • 130