I’m trying to figure out, why setting overflow-x: hidden to container makes my element with position: absolute hidden.
The effect is better understood in this demo.
https://codepen.io/Karina1703/pen/LYMzqEj
Here is the code:
.container {
overflow-x: hidden; /* If I remove this line everything is how I expect it to be! */
}
.box {
position: relative;
width: 160px;
}
.button {
width: 100%;
background-color: blue;
}
.menu {
position: absolute;
width: 160px;
top: 20px;
width: 100%;
background-color: green;
}
<body>
<div class="container">
<div class="box">
<button class="button">Button</button>
<nav class="menu">
<div>1</div>
<div>2</div>
</nav>
</div>
</div>
</body>
2
Answers
With
position: absolute
you tell that.menu
will not take place, so its size on the parent container is 0. As of docsY-size is computed from the
container
‘s elements excluding absolutely positioned elements but absolutely positioned elements will be visible only inside this container. Try addingtop:4px;left:10px;
to your.menu
CSS and it will appear.That is happening because currently your
div.container
has the width and height equal to the only relative element within it (which is the button). Since the navigation it’s positioned absolutely under the button it’s not visible.In order to understand the statement above we need to start by understanding how
position: absolute
works. When an element position is absolute it’s removed from the normal document flow, and no space is created for the element in the page layout. The element is positioned relative to its closest positioned ancestor (if any) or to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.source
With this in mind, we can now ensure that the height of the
div.container
anddiv.box
have always enough height to show the inner elements.Here is the codepen where the solution can be visualised.