CSS浮动,清除“行”浮动元素
我想创建一个“记分卡”网格来输出一些数据。如果每个 div.item 中的数据都具有相同的高度,则每个 div.item 上留下的简单浮动会提供一个漂亮的均匀布局,该布局可以根据浏览器大小很好地缩放。
然而,如果数据是可变的,每个 div 中的行数不同,那么元素浮动的方式会产生不均匀且混乱的输出。请参阅下面的代码示例。如果您使用以下内容创建页面,请将浏览器大小调整为大约 800 像素宽,以便框 1、2 和 3 在顶部创建一个“行”,然后是 4、5 和 6。如何将 7 下拉到下一行,以便它与 8 和 9 一起创建一行?
显然,如果您调整浏览器的大小,以便每行出现 4 个 div,则数字 9 是我想要分解到 5 以下的元素。是否有明显的我遗漏的内容,或者我是否需要使用一些 Javascript 来实现此目的?
div.item{
float:left;
width:220px;
background-color:#DBDBDB;
margin:8px;
}
h1, p{
padding:4px;
margin:0;
}
<div class='item'>
<h1>1</h1>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
<div class='item'>
<h1>2</h1>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
<div class='item'>
<h1>3</h1>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
I want to create a "scorecard" grid to output some data. If the data in each div.item is all the same height, then a simple float left on each div.item gives a nice even layout which scales up and down nicely depending on browser size.
If the data however is variable, a different number of lines in each div, then the way elements float gives an uneven and messy output. See code sample below. If you create a page with the below, resize the browser to about 800px wide so that box 1, 2, and 3 create a "row" on top, followed by 4, 5 and 6. How do I get 7 to drop down to the next line so it creates a row along with 8 and 9?
Obviously if you resize the browser so that 4 divs appear in each row, number 9 is the element I want to break down below 5. Is there something obvious I am missing or do I need to use some Javascript to achieve this?
div.item{
float:left;
width:220px;
background-color:#DBDBDB;
margin:8px;
}
h1, p{
padding:4px;
margin:0;
}
<div class='item'>
<h1>1</h1>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
<div class='item'>
<h1>2</h1>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
<div class='item'>
<h1>3</h1>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
"float: left;"
更改为"display: inline-block;
vertical-align: top;"
它将按照您的方式工作想。
示例: http://jsfiddle.net/yK9eY/2/
Change
"float: left;"
to"display: inline-block;
vertical-align: top;"
and it will work the way you want.
Example: http://jsfiddle.net/yK9eY/2/
用容器包裹所有 div 并给出
.container { Overflow: hide; }
或.container { Overflow: auto }
到它。第二种方法是用容器包装所有 div,然后将另一个 div 放在所有 div 的底部,并给出一个类名称,例如“clear”,并为其设置样式
.clear {clear: Both }
Wrap all divs with a container and give
.container { overflow: hidden; }
or.container { overflow: auto }
to it.The second way is wrap all divs with a container and put another div to bottom of all divs and give a class name such example"clear" and style it
.clear { clear: both }