Dan Abramov
Dan Abramov

Reputation: 268215

Why does an absolutely positioned child expand container height and how to prevent this?

Suppose you have a parent div that contains several normal children and one absolute child.

I've read practically everywhere that a child with position: absolute will not influence parent's height, since it is out of the normal flow. However in my case, an absolute element expands the parent, and I can't understand why.

(I tried reading the spec but I'm really lost.)

HTML

<div class="container">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="outsider"></div>
</div>

CSS

.container {
  overflow: hidden;
}

.block, .outsider {
  width: 100%;
  height: 1000px;
}

.block {
  background: red;
}

.outsider {
  position: absolute;
  left: 0;
  top: 3000px;
  background: green;
  opacity: 0.5;
}

CSS overflow

Why does the browser let me scroll past the element's supposed height? It seems consistent in Chrome, Safari and Firefox so I presume it's part of the spec.

How do I prevent this behavior? I'd like absolutely positioned element to be cropped if it doesn't fit into the container height “dictated” by “normal” children.

See it live.

Upvotes: 6

Views: 3769

Answers (1)

JesseEarley
JesseEarley

Reputation: 1032

You are missing a position on your parent container. Add

.container{
     position: relative;
}

The absolutely positioned element will go back up the DOM to find the nearest positioned parent, in this case you don't have one explicitly defined, so it's going back up to <body>

Upvotes: 4

Related Questions