user1334007 user1334007 - 4 months ago 54
CSS Question

Absolute positioning ignoring padding of parent

How do you make an absolute positioned element honor the padding of its parent? I want an inner div to stretch across the width of its parent and to be positioned at the bottom of that parent, basically a footer. But the child has to honor the padding of the parent and it's not doing that. The child is pressed right up against the edge of the parent.

So I want this:

enter image description here

but I'm getting this:

enter image description here

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

I can make it happen with a margin around the inner div, but I'd prefer not to have to add that.


First, let's see why this is happening.

The reason is that, surprisingly, when a box has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

Here is the relevant part of the CSS specification:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.

I think the most general-purpose solutions are:

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

  2. Repeat the padding 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 preprocessing tool like SASS or LESS you can avoid that problem by using a single variable for the paddings.