浮动div定位

Mic*_*ael 10 html css

我需要一个浮动矩形(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> 
Run Code Online (Sandbox Code Playgroud)

thi*_*dot 10

现场演示

  • 正如@Laxman13所建议的那样,您需要添加position: relative到"浮动矩形"的父级.在这种情况下,相关的父母恰好是body元素.
  • 阅读本/this/这个有助于了解该position物业.

HTML:

<div id="floatingRectangle">Hi.</div>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)


Lax*_*n13 9

添加position: relative;到矩形div的父级.这将从父元素的底部定位div 20px.