user740521
user740521

Reputation: 1204

Adding a border to floating element causes the last div to wrap

I have the following html/css. When I leave the borders off, everything lines up correctly, but if I put the borders on the center div then the right side's content shows up under everything else. How can I fix this?

#container {} #left {
  width: 20%;
  float: left;
}
#center {
  width: 60%;
  float: left;
  border-left: 1px solid black; /*this causes the 'right' div to wrap*/
  border-right: 1px solid black; /*this causes the 'right' div to wrap*/
}
#right {
  float: left;
  width: 20%;
}
<div id="container">
  <div id="left">I am left</div>
  <div id="center">I am center</div>
  <div id="right">I am right</div>
  <div style="clear: both;"></div>
</div>

Upvotes: 1

Views: 183

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122037

You need to add box-sizing: border-box so that the width of border is included in width of elements, otherwise its 60% + 1px + 1px + 2 * 20% and that is more then 100%.

#container > * {
  box-sizing: border-box;
}
#left {
  width: 20%;
  float: left;
}
#center {
  width: 60%;
  float: left;
  border-left: 1px solid black;
  border-right: 1px solid black;
}
#right {
  float: left;
  width: 20%;
<div id="container">
  <div id="left">I am left</div>
  <div id="center">I am center</div>
  <div id="right">I am right</div>
  <div style="clear: both;"></div>
</div>

Note: box-sizing: border-box will also include padding but not the margins.

Upvotes: 5

Saurav Rastogi
Saurav Rastogi

Reputation: 9731

Use CSS's calc() function. As you've assigned width: 60% to the #center when you're applying borders it is increasing the width by 2px, to compensate that:

#center {
  width: calc(60% - 2px);
}

Have a look at the snippet below:

#container{}
#left{
  width:20%;
  float: left;
}
#center {
  width: calc(60% - 2px);
  float: left;
  border-left: 1px solid black; /* this causes the 'right' div to wrap */
  border-right: 1px solid black; /* this causes the 'right' div to wrap */
}
#right {
   float: left;
   width: 20%;
}
<div id="container">
  <div id="left">I am left</div>
  <div id="center">I am center</div>
  <div id="right">I am right</div>
  <div style="clear: both;"></div>
</div>

Hope this helps!

Upvotes: 2

Related Questions