我有一个包装器类,其中包含网页上的所有内容。问题是如果内容是绝对放置的,它会占用我的页脚。我必须将内容放置为绝对定位。
页脚似乎无法识别内容是绝对的。这是我的代码
<style>
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -4em;
}
.footer, .push {
height: 4em;
}
</style>
</head>
<body>
<div class="wrapper">
<img src="activity/Chrysanthemum.jpg" style="z-index: 1; position:absolute; width: 420px; height: 400px; left: 100px;top:260px; ">
<div class="push">
</div>
</div>
<div class="footer" >copyrights</div>
</body>
如果我通过删除 position:absolute
属性来更改图像样式,一切看起来都很正常。所以我的问题是我们如何将页脚放置在绝对定位内容的底部?
最佳答案
更新的答案,关于评论。
正如我在之前的回答中提到的,使用纯 CSS 无法实现这种效果。因此,我将展示 JavaScript 方法。添加相关ID(参见 Fiddle ),并在正文末尾添加以下代码。此代码片段将在必要时调整包装器的大小。
注意:当页面小于窗口高度时,页面包装器仍将占据整个高度,因为绝对定位的元素无法区分高度变化.
<script>
(function(){
var wrapper = document.getElementById("wrapper");
var height = document.documentElement.scrollHeight;
wrapper.style.height = height + "px";
})();
</script>
上一个答案:
该问题是由于绝对定位元素不会影响其父元素的高度/宽度这一事实引起的。
要修复您的代码,请应用以下 CSS(仅显示相关 CSS,更新后附有描述性注释)。 fiddle :http://jsfiddle.net/4ja2V/
html, body {
height: 100%;
width: 100%;
padding: 0; /* Get rid off the padding */
}
.wrapper {
position: relative; /* Necessary to properly deal with absolutely positioned
child elements. */
height: 100%;
margin: 0 auto 4em; /* So that the content is visible when scrolled down*/
}
.footer {
height: 4em;
position: fixed; /* Positions your footer at a fixed position in the window*/
bottom: 0; /* At the bottom of the window*/
}
您在 .wrapper
中使用了负的底部边距,这导致该元素“吃掉”了页脚。当您使用绝对定位的内部元素时,没有可靠的纯 CSS 方法来获取 .wrapper
元素的实际宽度/高度。因此出现了 position:fixed
。
页脚被定义为具有 4em
的高度。由于页脚位于固定位置(即向下滚动时元素不会移动),因此有必要在包装元素的底部应用额外的边距。
关于html - 放置内容定位为绝对的页脚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865819/