如何使一个绝对定位元素尊重其父元素的填充?我想要一个内部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周围的边缘,但我宁愿不添加它。
首先,让我们看看为什么会这样。
原因是,令人惊讶的是,当一个方框具有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.