Search code examples
htmlcsscss-positionabsolute

How make children of absolutely positioned element disappear, when we set its height to zero?


I have div with class of 'box' inside my body. And that div contains another div with a class of 'box-inside'. I have set the absolute position on 'box' and set all inset properties to zero to make it span whole width of body. Now, I have set its height to zero but the box inside it does not disappear, it's still at its place. How to make inside box disappear with zero height?

.box {

  background: black;
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
  height: 0;
}
.box .box-inside {
  padding: 2em;
  background: #f4f4;
}

Change the height of '.box' to get a clear idea. Here is a link on Codepen: https://codepen.io/aqib-ali-01/pen/ZEyEWKE?editors=0100


Solution

  • Use the CSS property overflow. This property is placed on a container element (in your case the div with a class of box) and it controls the behavior of the content that is too big to fit in the container.

    To hide all the content that overflows a parent use overflow: hidden. Your CSS will look like the following.

    .box {
    
      background: black;
      position: absolute;
      left:0;
      right: 0;
      top: 0;
      bottom: 0;
      height: 0;
      overflow: hidden;
    }
    .box .box-inside {
      padding: 2em;
      background: #f4f4;
    }