Search code examples
htmlcssheadercontainerscenter

Centering div both vertically and horizontally inside of 100% width relatively positioned div


Have a div (really a header element) and I've seen many sites these days display text content perfectly centered within the container. So I'm trying it out, but so far, it's too far to the top of the div than the center. The example is here: http://jsfiddle.net/nuoxpmrk/

HTML:

<header class="entry-header" style="background: url(https://thecleverroot.com/wp-content/uploads/header-hudson-valley-foie-gras.jpg ) no-repeat top center!important; background-size: cover!important;">
  <section class="entry-caption">
    <h1 class="entry-title">Title Goes Here</h1><p class="entry-subtitle">This is a Subtitle</p> <p class="entry-credits">Written by: JS Fiddle</p>
  </section>
</header>

CSS:

.entry-header { position: relative; width: 100%; height: 640px; color: #FFF; }
.entry-caption { margin: 15% auto 0; padding: 32px; text-align: center; width: 100%; }
.entry-caption p.entry-subtitle { font-size: 18px; line-height: 1.25; text-transform: none; }
.entry-caption h1.entry-title { font-size: 38px; line-height: 1.25; }
.entry-caption p.entry-credits { font-size: 14px; line-height: 1; margin-bottom: 1em; text-transform: uppercase; }

Solution

  • You can keep this very simple with CSS Flexbox. You just need to add three lines of code, and you can get rid of a bunch of code, as well.

    Regardless of screen re-sizing vertically or horizontally, the centered items will remain centered.

    HTML (no changes)

    CSS

    .entry-header { 
        display: flex; /* establish flex container */
        justify-content: center; /* center child element (<section>) horizontally */
        align-items: center; /* center child element (<section>) vertically */
    
        /* No further changes */
    
        position: relative;
        width: 100%;
        height: 640px;
        color: #FFF;
    }
    
    .entry-caption { 
        /* margin: 15% auto 0; don't need this */
        /* padding: 32px; don't need this */
        text-align: center; 
        /* width: 100%; don't need this */
    }
    

    DEMO: http://jsfiddle.net/nuoxpmrk/2/

    Note that flexbox is supported by all major browsers, except IE < 10.