Search code examples
htmlcsscss-positionvertical-alignment

Two separate sentences to be placed in center of page vertically, across screen sizes, without over lapping


Centering horizontally was no problem but I am having trouble vertically. I want the two sentences to be in the middle of the page, no matter what size device is being used. I tried vertical-align with no success. I tried position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%); and ended up with them overlapping which makes sense but I can't figure out how to get around it.

<!DOCTYPE html>
<html>
<head>
<title>Jefferson's Virginia</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body  {
  background-color:#999;
}
P.one {
    margin-left: auto;
    margin-right: auto;
    max-width: 50%
    font-family: "Times New Roman", Times, serif; 
    font-size: 1.75em;
    font-weight: bold;
    text-align: center;
    }
P.two {
    margin-left: auto;
    margin-right:auto;
    max-width: 50%
    font-family: "Times New Roman", Times, serif; 
    font-size: 1.75em;
    font-weight: bold;
    text-align: center;
    }
    </style>
    </head>
<body>
<p class="one"> Jefferson's Virginia Website </p>
<br>
<p class="two"> In Process of Being Re-constructed </p>
</body>
</html>

Solution

  • 1) wrap all element in a wrapper HTML element

    <div class="wrapper"> ... </div>
    

    2) make height of body and html as 100%

    html, body{
        height: 100%;
    }
    

    3) Center the whole wrapper element using flexbox.

    .wrapper{
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
    

    html,
    body {
      height: 100%;
    }
    
    body {
      background-color: #999;
    }
    
    .wrapper {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      text-align: center;
    }
    
    p.one {
      font-family: "Times New Roman", Times, serif;
      font-size: 1.75em;
      font-weight: bold;
    }
    
    p.two {
      font-family: "Times New Roman", Times, serif;
      font-size: 1.75em;
      font-weight: bold;
    }
    <div class="wrapper">
      <p class="one"> Jefferson's Virginia Website </p>
      <br>
      <p class="two"> In Process of Being Re-constructed </p>
    </div>