Search code examples
htmlcssviewport-units

The 'top' CSS attribute does not apply with 100vh


I am attempting to build a, simple, single page website with only css as an exercise to familiarize myself with css.

I have three background images stacked on each other. Each image is set to a height of 100vh. This gives each image a nice look but I tried using the 'top' attribute to place text in the middle of the page, the text didnt move.

Can someone tell me why 'top' doesnt work in this circumstance? And a way to get around it?

This is my CSS: 

#page1 {
    background-size: cover;
    background-image: url('Page1_f09078_f06078_1000_vertical.png');
    height: 100vh;  
    display: block;
}

#welcome {
    text-align: center;
    top: 50%;                <-- This attribute won't work
}

#page2 {
    background-size: cover;
    display: block;
    background-image: url('Page2_f06078_ffa860_1000_vertical.png');
    height: 100vh;  
}

#page3 {
    background-size: cover;
    display: block;
    background-image: url('Page3_ffa860_f09078_1000_vertical.png');
    height: 100vh;
}

This is my html:

<html lang="en">
  <head>
  <link href="SinglePage.css" rel="stylesheet">
  </head>
    <body>

      <div id="page1">

        <h2 id="welcome">Welcome!</h2>


      </div> <!-- End of page1 -->

      <div id="page2">
      </div>

      <div id="page3">
      </div>



   </body>
</html>

Solution

  • top, left, right and bottom css properties work only when used with relative, absolute or fixed position.

    Use following css:

    #page1 {
      position: relative;
    }
    
    #welcome {
      transform: translateY(-50%);
      text-align: center;
      position: absolute;
      top: 50%;
      right: 0;
      left: 0;
    }