【发布时间】:2017-09-15 01:23:20
【问题描述】:
当我构建一个 2 列布局并让每行的第一个项目向左浮动时,我遇到了一个问题。如果元素的文本比预期的大得多,则行会中断,项目会被下推,所以它看起来不像这样:
看起来像这样:
代码是:
<ul class="layout">
<li>
<article>
<div class="thumb">
<img class="img" alt="" src="">
</div>
<div class="post-info">
<h3>Hey there! You should make me bigger to break the layout.</h3>
<p>Some text here...</p>
</div>
</article>
</li>
<li>
<article>
<div class="thumb">
<img class="img" alt="" src="">
</div>
<div class="post-info">
<h3>Hey there! You should make me bigger to break the layout.</h3>
<p>Some text here...</p>
</div>
</article>
</li>
<li>
<article>
<div class="thumb">
<img class="img" alt="" src="">
</div>
<div class="post-info">
<h3>Hey there! You should make me bigger to break the layout.</h3>
<p>Some text here...</p>
</div>
</article>
</li>
<li>
<article>
<div class="thumb">
<img class="img" alt="" src="">
</div>
<div class="post-info">
<h3>Hey there! You should make me bigger to break the layout.</h3>
<p>Some text here...</p>
</div>
</article>
</li>
CSS:
.layout {
list-style: none;
}
.layout > li {
vertical-align: top;
width: 49%;
}
.layout > li:nth-child(odd) {
margin-right: 1%;
float: left;
}
.layout > li:nth-child(even) {
margin-left: 1%;
float: right;
}
这行得通,但如果我们要做得更长,它就会坏掉。
如果我们添加这一行:
.layout > li:nth-child(even) + li {
clear: both;
}
无论我扔什么,它都能完美运行。
怎么会?
【问题讨论】:
-
会感谢有声誉的人可以编辑要嵌入的图像。
-
添加
float会创建一个新的块格式化上下文,应该清除来表示上下文已经结束...参见this -
@kukkuz 我明白了!但是我怎么还能保持 float: left 和 clear: both;在同一个项目上,如果我清除每三个(行的第一个)元素,为什么它会起作用?