如何使一个绝对定位元素尊重其父元素的填充?我想要一个内部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,并将其设置为红色,并将你的父级高度更改为200px,只是为了测试它。这个想法是,现在子变成了孙子,父变成了祖父。所以父结点尊重父结点。希望你明白我的意思。
<html>
<body>
<div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
<div style="background-color: red; position: relative; height: 100%;">
<div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
</div>
</div>
</body>
</html>
编辑:
我觉得你想做的事是做不到的。绝对位置意味着你要给它必须遵守的坐标。如果父元素的填充是5px。然后你把子图层放在最上面:-5px;左:5 px。怎么能同时尊重父母和你呢?
我的解决方案
如果你想让它尊敬父母,不要绝对定位它。
首先,让我们看看为什么会这样。
原因是,令人惊讶的是,当一个方框具有position: absolute时,它的包含方框是父方框的填充方框(即围绕其填充的方框)。这是令人惊讶的,因为通常(也就是说,当使用静态或相对定位时)包含框是父内容框。
下面是CSS规范的相关部分:
在祖先是内联元素的情况下,包含块是为该元素....生成的第一个和最后一个内联框的填充框周围的包围框否则,包含块由祖先的填充边形成。
最简单的方法——正如Winter的回答中建议的那样——是在绝对定位的div上使用padding: inherit。不过,只有当你不希望绝对定位的div有任何自己的额外填充时,它才有效。我认为最通用的解决方案(两个元素都可以有自己独立的填充)是:
Add an extra relatively positioned div (with no padding) around the absolutely positioned div. That new div will respect the padding of its parent, and the absolutely positioned div will then fill it.
The downside, of course, is that you're messing with the HTML simply for presentational purposes.
Repeat the padding (or add to it) on the absolutely positioned element.
The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS or LESS you can avoid that problem by using a variable. This is the method I personally use.