Kalpesh Singh
Kalpesh Singh

Reputation: 1717

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)

Upvotes: 1

Views: 1280

Answers (3)

user5730434
user5730434

Reputation:

Refer to this tutorial. It teaches in an easy manner how to vertically center elements.

Upvotes: 0

symlink
symlink

Reputation: 12209

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/

Upvotes: 2

Saeed Salam
Saeed Salam

Reputation: 467

Give position:relative to that light blue (wrapper div).

and add following css for the div you want to center:

position: absolute;
top: 50%;
left: 50%;
width: 100%;
-moz-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;

Hope that helps!

Upvotes: 1

Related Questions