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

时间:2016-11-15 02:42:05

标签: css css-float padding

3向左浮动的柱子,每个柱子宽度为33.33%。我添加了填充以使列看起来更整洁。但显然最后的DIV被推到了新的界限。这个解决方案吗?在这里,我还提供了复制品供参考。

* {
  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>

4 个答案:

答案 0 :(得分:1)

不幸的是,填充在默认情况下不会计入大小,因此宽度+填充使每个实际上宽于第三个。 box-sizing: border-box是一个很好的工具来解决这个问题,所有填充和填充边界宽度测量的一部分:

* {
  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>

答案 1 :(得分:1)

使用box-sizing: border-box,它会强制提供的尺寸为完整尺寸,包括任何顺序和间距,例如填充。

&#13;
&#13;
* {
  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
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

这是因为填充。尝试添加box-sizing: border-box;,这将在声明填充时保留容器width

&#13;
&#13;
* {
  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;
  box-sizing: border-box;
}

.ful-dark {
  opacity:0.9
}

.mid-dark {
  opacity:0.8
}

.lil-dark {
  opacity:0.7
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

你想要3 *(padding-right + padding-left + width)等于100%。

尝试

.col {
  float:left;
  width:31.33%;
  background:#333;
  color:#fff;
  text-align:center;
  position:relative;
  padding:1%;
}