清除 CSS 中浮动元素的最佳方法是什么?
目前认为清除 CSS 浮动元素的最佳方法是什么:
- 保持 HTML 标记的语义并尽可能消除不必要的元素,并且
- 成为对大多数浏览器可靠工作的跨浏览器、跨平台解决方案?
What is currently considered the best way to clear CSS floated elements that will:
- Keep the HTML markup as semantic and free of unnecessary elements as possible, and
- Be a cross-browser, cross-platform solution that works reliably for the majority of browsers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是一个图形设计问题。它是 CSS 的,所以属于 StackOverflow。
也就是说,保持 HTML 干净的答案就是给父级提供溢出。因此,如果您的标记是:
您可以给包装器一个溢出:
现在
.wrapper
将包含两个浮点数。这通常就是所需要的全部。
有时,在较旧的 IE 中,容器也需要宽度。
This isn't a graphic design question. It's a CSS one, so belongs on StackOverflow.
That said, the answer for keeping the HTML clean is simply to give the parent an overflow. So if your markup is:
you can give wrapper an overflow:
And now
.wrapper
will contain both the floats.That's usually all that is needed.
Sometimes, in older IEs, the container also needs a width.
您可以使这个过程变得更复杂,但一个简单的方法是在 CSS 中添加一个名为 .clearfix 的类,并带有此属性:
然后只需在要清除的内容下方插入一个标签即可。
谷歌clearfix以更现代的方式定义标签。
You can make this more complicated, but a simple way is to add a class to your CSS called .clearfix with this attribute:
Then just insert a tag underneath what you want to clear.
Google clearfix for more modern ways to define the tag.
我见过的最好的方法是使用 :before & :after 伪元素适用于现代浏览器,zoom: 1 适用于旧版本的 IE。
更多信息请点击这里:
http://nicolasgallagher.com/micro-clearfix-hack/
The best method I've seen for this is using :before & :after pseudo elements for modern browsers and zoom: 1 for older versions of IE.
More info here:
http://nicolasgallagher.com/micro-clearfix-hack/
有点棘手,但它适用于现代浏览器:)
a little tricky, but it's work for modern browser :)