Search code examples
csslayoutcenterviewportstyling

Vertically center in viewport using CSS


I am looking to vertically center a <div> in the viewport (browser window) without resorting to Javascript (pure HTML and CSS only). I have several constraints:

  • The div must be centered vertically in the viewport. Methods I have seen only support centering inside another <div>, which is not what I want.
  • The height of the div is not known.

Other constraints:

  • The div must be aligned to the right.
  • The div has a constant width.
  • The div must support padding.
  • Other elements will be placed on the web page. The div acts as a menu.
  • The div must support a background colour/image.

This gets me close to what I want, but not exactly:

#nav {
    position: fixed;
    right: 0;
    top: 50%;
}

However, the top of the nav is in the middle, not the middle of the nav.

Is there some technique which allows me to center my div with these constraints?


Solution

  • you can use this as one of the solution.

       <style>
       #containter {
         height: 100vh; //vh - viewport height
         display: flex;
         flex-direction: column;
         align-items: center; 
         justify-content: center;
       }
       #content {}
      </style>
    
     <div id="containter">
      <div id="content">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
     </div>
    </div>