Home > Mobile >  why 100% or 100vh height not occupying full page height
why 100% or 100vh height not occupying full page height

Time:08-05

I was learning css pseudo-selector class ::before. I am confused how come 100% value given to height property of background-color not actually occupying full page height. I tried with viewport height also. Same issue. Below is my code:

* {
  margin: 0;
  padding: 0;
}

 :root {
  --navbar-height: 59px;
}

#navbar {
  display: flex;
  align-items: center;
  border: 2px solid red;
}

#navbar ul {
  display: flex;
}

#navbar::before {
  content: "";
  background-color: black;
  position: absolute;
  /* height being 100% or 100vh not occupying full page */
  height: 100vh;
  width: 100%;
  z-index: -1;
  opacity: 0.4;
}

#navbar ul li {
  list-style: none;
  font-size: 1.3rem;
}

#navbar ul li a {
  display: block;
  padding: 3px 22px;
  border-radius: 20px;
  text-decoration: none;
}
<nav id="navbar">
  <ul>
    <li ><a href="#">home</a></li>
    <li ><a href="#">services</a></li>
    <li ><a href="#">contactus</a></li>
  </ul>
</nav>

output

enter image description here

what I expected was black background-color because have been given 100% height will occupy whole page. But it didn't happen. Why is it so?

CodePudding user response:

The issue is due to display: flex; on #navbar. Remove that and you should be fine. Another solution is wrapping the navbar in a parent div and adding :: before on it.

CodePudding user response:

You just need to position your :before correctly. Add below CSS to your #navbar::before and you should be set:

top: 0;
left: 0;

CodePudding user response:

Because your positioning is absolute you need to check the top and left properties.

I replicated your code and then opened the chrome dev tools as shown in the attached screenshot. If you open the computed tab you will see that the top property is -516.378px.

You can do this by clicking Elements>Computed which will show you all the properties after the browser has calculated them.

chrome Devtools

If you add top: 0; as shown below you can override the calculated css position.

#navbar::before {
  content: "";
  background-color: black;
  position: absolute;
  /* height being 100% or 100vh not occupying full page */
  height: 100vh;
  width: 100%;
  top: 0;
  z-index: -1;
  opacity: 0.4;
}

Here's a stackblitz example you can play with to try it out yourself:

https://stackblitz.com/edit/js-82vdk5?file=style.css

  • Related