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.
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.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally 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%.
Add d-flex align-items-center justify-content-center classes to the parent element to center its content vertically and horizontally.
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 .
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With