Search code examples
htmlcssalignment

Vertically center a block in CSS


I'm trying to achieve following result:

enter image description here

How can I vertically align 2nd block to the middle of page. (In mobile devices too)


Solution

  • Flexbox to the rescue. Given a simple html layout like this:

    <header></header>
    <main>
        <h1>Heading</h1>
        <h2>Sub Heading</h2>
        <div>
            <a href="#">Click Me</a>
            <a href="#">Click Me</a>
        </div>
    </main>
    <footer></footer>
    

    You can center the contents in <main> with a few lines of code:

    main {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-flow: column;
    }
    

    The first rule establishes the flexbox context, the middle style rules align the content vertically and horizontally, and the last rule makes sure the items are aligned top to bottom, not left to right. Since the anchor buttons are contained within a div, the div itself is what's being aligned by flexbox, and the buttons are free to sit side by side.

    https://jsfiddle.net/858vr2hf/

    EDIT:

    Updated fiddle with background image:

    https://jsfiddle.net/s3dytc31/