Search code examples
htmlcssvertical-alignment

100% viewport vertical center with content following


I am looking to accomplish a few things-

  1. Set a container to fit 100% of viewport height and width;
  2. Center the h1 vertically and horizontally in that container;
  3. Add a paragraph of text beneath the h1 without this paragraph pushing the h1 up or breaking the centering.

Here's a diagram

I've already tried many of the methods discussed here and elsewhere (tables, display: table/table-cell + vertical align, using an inline-block with vertical align, etc) but the problem is that all of them either center both the h1 and the paragraph, or adding the paragraph under the h1 breaks it entirely. As the site is responsive, the h1 will likely become multiple lines of text on smaller screens. Is there a way to keep the h1 at the vertical and horizontal center while still adding content beneath it?


Solution

  • The use of flexbox is your best bet as it is very concise and has good browser support. Also, it's your best bet for future-thinking as it is forming the foundation of today's modern app layout infrastructure.

    The <p> being not pushed down is just done by giving a 0 height so that its effects on its container is not realized.

    HTML:

    <div class="container">
        <h1>
            HI
        </h1>
        <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras neque tortor, auctor ut consectetur non, posuere a justo. Morbi nisi eros, pellentesque eget ullamcorper eu, tristique at tortor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent ornare odio lorem, vel fermentum est lacinia ut. Vivamus tincidunt augue scelerisque justo consectetur tincidunt. Phasellus lectus nibh, ultrices in dictum vel, pretium at nisl. Sed vehicula tortor sed facilisis accumsan. Sed cursus felis quis quam efficitur, id luctus mi aliquet. Morbi mattis gravida convallis. Sed non feugiat dolor, in gravida arcu. Morbi id dolor imperdiet, rhoncus ante convallis, varius lacus.
        </p>
    </div>
    

    CSS:

    .container {
        align-items: center;
        background: red;
        display: flex;
        flex-direction: column;
        justify-content: center;
        height: 100vh;
        width: 100vw;
    }
    
    .container p {
        height: 0;
    }
    

    Fiddle: https://jsfiddle.net/3ms3sggd/

    A Great Flexbox Guide: https://css-tricks.com/snippets/css/a-guide-to-flexbox/