css3

CSS Positions: Keeping an Absolute Element Inside its Parent

In CSS, when you style an element with position: absolute, you'll often notice that said element will teleport outside of its parent and float happily on its own, sometimes even totally offscreen. This might've been enough to scare you off absolute positioning altogether, but I'm here to coax you back.

Synopsis

What the heck is going on?

When researching CSS absolute positioning, you may see a lot of forum posts saying its impossible to position an element inside of a parent if position: absolute is set. That is a misconception that is widely spread. While this is the behavior that is often seen, this only applies to elements whose parents don't have their own position set.

The truth is that an absolute positioned element will be positioned relative to the closest ancestor that has its position property set. If no ancestors have their position property configured, then it will be positioned relative to the page as a whole. This is what most people end up seeing which leads to the misconception.

If you'd like more info on the CSS position property, check out CSS Layout - The Position Property from W3schools.

Don't put child in the corner

An Absolute Child

The following image and accompanying CSS shows a child div configured with position: absolute. You'll notice that the child div has floated outside of the borders of its parent.

child-absolute
Child position: absolute

#parent {
  border: 3px solid black;
  display: inline-block;
  padding: 4em;
  margin: 1em;
}
#child {
  border: 3px solid blue;
  color: blue;
  top: 0;
  left: 0;
  position: absolute;
}

An Absolute Child With a Relative Parent

Now take a look at what happens when we add position: relative to the parent div. You'll see the child div has now been magically rangled in by its parent.

parent relative
Child position: absolute, Parent position: relative

#parent {
  border: 3px solid black;
  display: inline-block;
  padding: 4em;
  margin: 1em;
  position: relative; /* Only CSS property changed */
}
#child {
  border: 3px solid blue;
  color: blue;
  top: 0;
  left: 0;
  position: absolute;
}

That's all that needs to be done to keep an absolute positioned element inside of its parent. You can then set its position anywhere relative to its parent. If you'd like to play around with the position property yourself, have at it with this JSFiddle.

Please Share Me, I'm Lonely