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


Tags: css,scroll,overflow,css-position,absolute

Problem :

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.



Solution :

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>


    CSS Howto..

    How to delay the display of the background image in a div

    Anyone know how to create CSS rectangle with one corner chopped off?

    How to adjust font awesome down arrow via css

    css: how to surround an image with two other images vertically centered around the first one?

    Show/Hide tr elements based on multiple CSS classes and input from multiple checkboxes

    CSS - How can I set the content to attr() but when attribute isn't available, set it to 0 or another?

    How do I customize