Search code examples
htmlcssvertical-alignmentviewportviewport-units

Viewport Centered <div> Alignment


I am trying to center content vertically in a viewport using vh units, and would like to have a second <div> aligned below and right, but still centered vertically in the viewport.

In other words, I'd like to have the .reference class aligned right and below the .content class, and both elements centered vertically in the viewport.

body {
  background: rgb(0, 14, 32);
  color: white;
  font-size: 2em;
}

.card { /* Should be vertically centered in viewport*/
  height: calc(100vh);
  display: flex;
  align-items: center;
  justify-content: center;
}

.content { /* Should be horizontally left aligned or centered in viewport*/
  float: left;
  border: solid white;
  margin: 2 em;
}

.reference { /* Should be right aligned and below .content <div> in viewport*/
  float: right;
  clear: both;
  text-align: right;
  font-size: 0.5em;
  margin: 2 em;
  border: solid blue;
}
<div class="card">
  <div class="content">
    Main Content
  </div>
  <div class="reference">
    Reference Content
  </div>
</div>

Updated for final solution

body {
  background: rgb(0, 14, 32);
  color: white;
  font-size: 2em;
  display: table;
  width: 100%;
}

.card { /* Should be vertically centered in viewport*/
  height: calc(100vh);
  display: table-cell;
  vertical-align: middle;
  margin: auto;
}

.content { /* Should be left or center aligned in viewport*/
  text-align: left;
  border: solid white;
  margin: 0 1rem;
}

.reference { /* Should be right aligned and below .content <div> in viewport*/
  text-align: right;
  font-size: 0.5em;
  border: solid blue;
  margin: 0 1rem;
}
<div class="card">
  <div class="content">
    Main Content
  </div>
  <div class="reference">
    Reference Content
  </div>
</div>


Solution

  • To achieve expected result, use below
    HTML:

     <div class="card">
          <div class="content">
            Main Content
          </div>
          <div class="reference">
            Reference Content
          </div>
        </div>
    

    CSS:

    body {
      background: rgb(0, 14, 32);
      color: white;
      font-size: 2em;
       display: table;
       width:100%;
      text-align:center;
    
    }
    
    .card {
      height: calc(100vh);
     display: table-cell;
     vertical-align: middle;
      margin: auto;
    
    
    }
    
    .content {
      text-align: left;   
      border: solid white;
    
    }
    
    .reference {
      text-align: right;
      font-size: 0.5em;
      border: solid blue;
    
    }
    

    Codepen- https://codepen.io/nagasai/pen/qmVKjB