faliqaiman faliqaiman - 19 days ago 8
CSS Question

CSS - Float Left + Padding = Last Div Go Down?

3 Column with float left, each with 33.33% width. And I added padding to make the column looks more neat. But apparently the last DIV is pushed to new line. Any solution for this one? Here also I come out with reproduction for reference.



* {
padding:0;
margin:0;
}
.row {
width:80%;
display:block;
margin:40px auto;
background: #f3f3f3;
overflow:auto;
}
.col {
float:left;
width:33.33%;
background:#333;
color:#fff;
text-align:center;
position:relative;
padding:20px
}

.ful-dark {
opacity:0.9
}

.mid-dark {
opacity:0.8
}

.lil-dark {
opacity:0.7
}

<div class="row">
<div class="col ful-dark"><h1>One</h1></div>
<div class="col mid-dark"><h1>Two</h1></div>
<div class="col lil-dark"><h1>Three</h1></div>
</div>




Answer

Padding unfortunately doesn't count by default in sizing, so the width + padding makes each actually wider than a third. box-sizing: border-box is a wonderful tool to combat this, making all padding & borders part of the width measurement:

* {
  padding:0;
  margin:0;
  box-sizing: border-box;
}
.row {
  width:80%;
  display:block;
  margin:40px auto;
  background: #f3f3f3;
  overflow:auto;
}
.col {
  float:left;
  width:33.33%;
  background:#333;
  color:#fff;
  text-align:center;
  position:relative;
  padding:20px
}

.ful-dark {
  opacity:0.9
}

.mid-dark {
  opacity:0.8
}

.lil-dark {
  opacity:0.7
}
<div class="row">
  <div class="col ful-dark"><h1>One</h1></div>
  <div class="col mid-dark"><h1>Two</h1></div>
  <div class="col lil-dark"><h1>Three</h1></div>
</div>

Comments