清除 CSS 中浮动元素的最佳方法是什么?

发布于 2024-12-13 12:18:41 字数 118 浏览 1 评论 0原文

目前认为清除 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

锦爱 2024-12-20 12:18:41

这不是一个图形设计问题。它是 CSS 的,所以属于 StackOverflow。

也就是说,保持 HTML 干净的答案就是给父级提供溢出。因此,如果您的标记是:

<div class="wrapper">
    <div style="float: left;"></div>
    <div style="float: left;"></div>
</div>

您可以给包装器一个溢出:

.wrapper {overflow: auto}

现在 .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:

<div class="wrapper">
    <div style="float: left;"></div>
    <div style="float: left;"></div>
</div>

you can give wrapper an overflow:

.wrapper {overflow: auto}

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.

似狗非友 2024-12-20 12:18:41

您可以使这个过程变得更复杂,但一个简单的方法是在 CSS 中添加一个名为 .clearfix 的类,并带有此属性:

.clearfix {clear: both;}

然后只需在要清除的内容下方插入一个标签即可。

谷歌clearfix以更现代的方式定义标签。

You can make this more complicated, but a simple way is to add a class to your CSS called .clearfix with this attribute:

.clearfix {clear: both;}

Then just insert a tag underneath what you want to clear.

Google clearfix for more modern ways to define the tag.

花海 2024-12-20 12:18:41

我见过的最好的方法是使用 :before & :after 伪元素适用于现代浏览器,zoom: 1 适用于旧版本的 IE。

/* For modern browsers */
.cf:before,
.cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

/* For IE 6/7 (trigger hasLayout) */
.cf {
    zoom:1;
}

更多信息请点击这里:
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.

/* For modern browsers */
.cf:before,
.cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

/* For IE 6/7 (trigger hasLayout) */
.cf {
    zoom:1;
}

More info here:
http://nicolasgallagher.com/micro-clearfix-hack/

涙—继续流 2024-12-20 12:18:41

有点棘手,但它适用于现代浏览器:)

.wrapper::after {
    content:"";
    clear:both;
}

a little tricky, but it's work for modern browser :)

.wrapper::after {
    content:"";
    clear:both;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文