可以使用CSS清除绝对定位的元素吗?

时间:2012-10-10 14:00:30

标签: html css css-position clear

有没有办法用CSS清除绝对定位的元素?我正在创建一个页面,我需要将网站的每个部分(部分元素)绝对定位,并且我想应用一个内容低于这些元素的页脚。
试图相对定位页眉和页脚来查看如果考虑总高度,但页脚仍然被“困”在截面元素下面。有什么想法吗?

<header style="position: relative;"></header>

<div id="content" style="position: relative;">

    <section id="a" style="position: absolute;"></section>

    <section id="b" style="position: absolute;"></section>

    <section id="c" style="position: absolute;"></section>

    <section id="d" style="position: absolute;"></section>

    <section id="e" style="position: absolute;"></section>

</div>

<footer style="position: relative;"></footer>

4 个答案:

答案 0 :(得分:18)

绝对定位的元素不再是布局的一部分 - 父项不知道绝对定位的子元素有多大。您需要自己设置“内容”的高度,以确保它不与页脚重叠。

答案 1 :(得分:4)

不要对布局使用绝对定位的元素,因为这些元素会从正常流中移除,不再影响它们周围的元素。而且他们不受其他因素的影响。

在条件允许的情况下,使用绝对定位来移动容器中的元素。

对于浮动元素,我建议您使用名为clearfix的特定清除技术。我虔诚地使用它。

http://nicolasgallagher.com/micro-clearfix-hack/

http://jsfiddle.net/necolas/K538S/

答案 2 :(得分:2)

有同样的问题,让所有绝对定位,但让第一个是相对的,至于高度确实改变的响应式布局,它确实有助于跟踪元素高度变化,注意在这种情况下所有元素具有相同的高度:

&#13;
&#13;
.gallery3D-item {
    position: absolute;
    top: 0;
    left: 0;
}
.gallery3D-item:first-of-type {
    position: relative;
    display: inline-block;
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我发现了一种this的简单解决方案,它可能无法涵盖所有​​可能的问题,但至少可以解决我的问题。

HTML:

<p>Content before</p>
<div class="offset-wrapper">
    <div class="regular">
        <img src="https://www.gravatar.com/avatar/bdf0bf75e96fa18e57769865ebeb9a6e?s=48&d=identicon&r=PG" />
    </div>
    <div class="special">
        <img src="https://www.gravatar.com/avatar/bdf0bf75e96fa18e57769865ebeb9a6e?s=48&d=identicon&r=PG" />
    </div>
</div>
<p>Content after</p>

CSS:

.offset-wrapper {
  background: green;
  position: relative;
  width: 100px;
}
.offset-wrapper .regular {
  visibility: hidden;
}
.offset-wrapper .special {
  bottom: -15px;
  left: -15px;
  position: absolute;
}