如何使一个绝对定位元素尊重其父元素的填充?我想要一个内部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中使用边距而不是填充:http://blog.vjeux.com/2012/css/css-absolute-position-taking-into-account-padding.html

你可以尝试使用下面的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上都可以运行。

首先,让我们看看为什么会这样。

原因是,令人惊讶的是,当一个方框具有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.

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

.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>

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

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

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