Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest method for vertical+horizontal centering of a div in the window?

Given a div with known dimensions, say width: 300px; height: 200px, what is the easiest method to place it in the middle of the screen both vertically and horizontally ? Example here

I'm interested in latest Firefox (no need for IE hacks).

CSS only please, no Javascript.

like image 234
Misha Moroshko Avatar asked Oct 11 '10 00:10

Misha Moroshko


People also ask

How do you center a div horizontally and vertically?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you center something vertically and horizontally?

To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.

How do you make a div vertically centered?

you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%.

How do I make my div center vertically and horizontally in bootstrap?

Add d-flex align-items-center justify-content-center classes to the parent element to center its content vertically and horizontally.


2 Answers

Position it 50% from the window/parent container and use a negative margin size that's half of the elements width/height :)

position: absolute; // or fixed if you don't want it scrolling with the page.
width: 300px;
height: 200px;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -100px;

You might need to set height: 100%, on both the body and html

html, body {
    height: 100%;
}

Edit: Here's a working example .

like image 105
Marko Avatar answered Oct 03 '22 10:10

Marko


Without supporting IE, this is actually pretty easy to achieve using display: table and display: table-cell.

Here's an update to your HTML:

<div id='my_div'>
    <div class="centered">this is vertically centered</div>
</div>

CSS:

body, html
{
    height: 100%;
}
body
{
    margin: 0;
    padding: 0;
    border: 1px solid blue;
}
#my_div
{
    width: 300px;
    border: 1px solid red;
    margin-left: auto;
    margin-right: auto;
    height: 100%;
    display: table;
    overflow: hidden;
}
.centered
{
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

And to preview: http://jsfiddle.net/we8BE/

like image 22
wsanville Avatar answered Oct 03 '22 12:10

wsanville