Html 浮动div定位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5399581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:31:33  来源:igfitidea点击:

Floating div positioning

csshtml

提问by Michael

I need a floating rectangle (100% width, 100px height) to appear exactly 20px above the bottom of a page. How can I do that?

我需要一个浮动矩形(宽度为 100%,高度为 100 像素)以恰好位于页面底部上方 20 像素处。我怎样才能做到这一点?

The code below shows the rectangle at the bottom of the browser window not the page - so if the page is taller than what can fit in the screen, the rectangle appears somewhere in the middle of the page.

下面的代码显示了浏览器窗口底部的矩形而不是页面 - 所以如果页面比屏幕高,矩形会出现在页面中间的某个地方。

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

采纳答案by Laxman13

Add position: relative;to the rectangle div's parent. This will position the div 20px from the bottom of the parent element.

添加position: relative;到矩形 div 的父级。这会将 div 定位在距离父元素底部 20px 的位置。

回答by thirtydot

Live Demo

现场演示

  • As suggested by @Laxman13, you need to add position: relativeto the parent of the "floating rectangle". The relevant parent in this case just happens to be the bodyelement.
  • Read this/ this/ thisto help understand the positionproperty.
  • 正如@Laxman13 所建议的,您需要添加position: relative到“浮动矩形”的父级。在这种情况下,相关的父body元素恰好是元素。
  • 阅读此//以帮助了解该position属性。

HTML:

HTML:

<div id="floatingRectangle">Hi.</div>

CSS:

CSS:

body {
    position: relative
}
#floatingRectangle {
    z-index: 1;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 20px;

    height: 100px;

    background-color: #000;
    color: white;

    padding: 0;
}