如何使一个绝对定位元素尊重其父元素的填充?我想要一个内部div伸展横跨其父的宽度,并被定位在该父的底部,基本上是一个页脚。但是子进程必须尊重父进程的填充,而它并没有这样做。孩子被压在父母的边缘上。

所以我想要这个:

但我得到了这个

< html > <身体> < span style=" font - family:宋体;填充:10 px;位置:相对;身高:100 px;" > < span style=" font - family:宋体;位置:绝对的;左:0 px;右:0 px;底部:0 px;div css sux " > < / > < / div > < /身体> < / html >

我可以让它发生在内部div周围的边缘,但我宁愿不添加它。


当前回答

可以用额外的Div级别轻松完成。

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

演示:https://jsfiddle.net/soxv3vr0/

其他回答

可以用额外的Div级别轻松完成。

<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
  <div style="position: absolute; left: 0px; right: 0px; bottom: 10px; padding:0px 10px;">
    <div style="background-color: gray;">css sux</div>
  </div>
</div>

演示:https://jsfiddle.net/soxv3vr0/

你可以尝试使用下面的css:

.child-element {
    padding-left: inherit;
    padding-right: inherit;
    position: absolute;
    left: 0;
    right: 0;
}

它让子元素从父元素继承padding,然后子元素可以被定位为匹配父元素的width和padding。

此外,我使用box-sizing: border-box;对于所涉及的元素。

我还没有在所有浏览器上测试过这个功能,但它似乎在Chrome、Firefox和IE10上都可以运行。

我将这样设置子节点的宽度:

.child{位置:绝对;宽度:calc(100% - padding);}

填充,在公式中,是左右父填充的和。我承认它可能不是很优雅,但在我的例子中,一个具有覆盖功能的div,它是有效的。

添加填充:继承你的绝对位置

.box{ background: red; position: relative; padding: 30px; width:500px; height:200px; box-sizing: border-box; } <div class="box"> <div style="position: absolute;left:0;top:0;padding: inherit">top left</div> <div style="position: absolute;right:0;top:0;padding: inherit">top right</div> <div style="text-align: center;padding: inherit">center</div> <div style="position: absolute;left:0;bottom:0;padding: inherit">bottom left</div> <div style="position: absolute;right:0;bottom:0;padding: inherit">bottom right</div> </div>

在父div中使用边距而不是填充:http://blog.vjeux.com/2012/css/css-absolute-position-taking-into-account-padding.html