Search code examples
htmlcssbackgroundcss-positionbackground-color

Why do parent elements sometimes not cover the children's dimensions?


Codepen link: https://codepen.io/lolcatBH/pen/OJbgLyd

I have the following html:

<div id="page">
  <div class="overlay"></div>
  <div class="click">SHOW POPUP</div>
  <div class="popup">
    <h1>Korean language</h1>
    <button class ="close">X</button>
    <div class="desc">Korean (North Korean: 조선말/朝鮮말, chosŏnmal; South Korean: 한국어/韓國語, hangugeo) is an East Asian language spoken by about 77 million people.</div>
  </div>
</div>

And CSS:

#page {
  position: absolute;
  top: 50%;
  left: 25%;
}

.popup {
  width: 300px;
  height: 300px;
  border: 1px solid black;
  z-index: 1;
  position: absolute;
  top: -10%;
  transform: scale(0);
  padding: 20px;
}

#page .overlay {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.7);
  z-index: 1;
  display: none;
}

#page.active .overlay {
  display: block;
}

.popup.active {
  transform: scale(1);
  background-color: white;
}

.close {
  position: absolute;
  right: 0%;
  top: 0%;
  color: white;
  background: black;
  border-radius: 50%;
}

.click {
  border: 1px solid black;
  padding: 20px;
  font-size: 20px;
  text-align: center;
  z-index: 0;
  cursor: pointer;
}

h1, desc {
  text-align: center;
}

JS:

const click = document.querySelector('.click');
const x = document.querySelector('.close');
const page = document.querySelector('#page');
const popup = document.querySelector('.popup');

const showPopup = () => {
  page.classList.toggle('active');
  popup.classList.add('active');
}

const hidePopup = () => {
  page.classList.toggle('active');
  popup.classList.remove('active');
}

click.addEventListener('click', showPopup);
x.addEventListener('click', hidePopup);

At first, what I tried to do is instead of creating a separate overlay div, I was going to put a background color on the #page element. However, in effect, the background only applies to the button element (.click). I don't actually understand why in this case, since the background-color doesn't seem to affect the .popup element.

Imgur: https://i.sstatic.net/VT10d.jpg

So my question is, why does the #page element not cover all of its children's width and height? In this case, I thought it would have cover the whole page. I've also tried putting width: 100vw and height:100vh but it in turn only applied the dimensions to the button.

Imgur: https://i.sstatic.net/PwgbA.jpg


Solution

  • The reason is that most of your elements have position set to absolute or fixed, which makes them completely (fixed) or partly (absolute) independent from their parent, i.e. there is no space of its own reserved for them, therefore they typically overlap other elements.

    So the parent doesn't span or cover them, but only those elements which don't have a set position or which have position: relative or static.