浮动div定位

13

我需要一个浮动矩形(宽度为100%,高度为100px),要求其距离页面底部恰好有20px的距离。如何实现呢?

下面的代码将矩形展示在浏览器窗口的底部,而不是页面的底部,因此如果页面高度超过屏幕高度,矩形会在页面中间某处出现。

<div style="z-index: 1; position: absolute; right: 0px; bottom: 20px; background-color: #000000; width: 100%; height: 100px; padding: 0px; color: white; ">&nbsp;</div> 

你能展示一下包含它的元素吗? - Surreal Dreams
2个回答

17
  • 如@Laxman13所建议,您需要将position: relative添加到"浮动矩形"的父级元素中。在这种情况下,相关的父级元素恰好是body元素。
  • 点击此处 / 此处 / 此处了解更多有关position属性的信息。

body {
  position: relative
}

#floatingRectangle {
  z-index: 1;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 20px;
  height: 100px;
  background-color: #000;
  color: white;
  padding: 0;
}
<div id="floatingRectangle">
  <h2>Hello</h2>
</div>
Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />

演示


转念一想,你确定你不只是想要一个固定页脚吗?请参考:http://ryanfait.com/sticky-footer/ - thirtydot
注意:此答案将原问题中的浮动div从“position: absolute;”更改为“position: fixed;”。根据您的需求,这会产生不同的效果。在我的情况下,只有“absolute”可以正确滚动。--如果一个不起作用,请尝试另一个。另请参阅上面给出的关于“position”的链接集合。 - BCS

11
position: relative; 添加到矩形 div 的父元素。这将使该 div 距离父元素底部 20 像素的位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接