Reputation: 3273
I'm sure this has been asked before, but all the questions I can find are far too complex. Really simply, how do I align a div container to the center and middle of a page both horizontally and vertically, so that it also stays there when the page is resized as well.
All I need is a blank browser window with a div that stays in the center of the screen when the window is resized, no matter what. Horizontal align is quite easy using margin:auto
but it's the vertical align that seems to be troublesome.
A lot of 'solutions' require that there first be a set height that the div is floating in. I'm sure there's got to be a simpler way...
Upvotes: 0
Views: 208
Reputation: 39
set margin: 0 auto; to the container for horizontal alignment.For vertical adjustment you can use margin-top property.If you require a vertical align than adjustment you can use javascript or jquery. First find the height of the browser window using jquery.Then adjust the margin-top(In a ratio) css property as the window height is changed.You can set an event for detecting the changes of window size.
Upvotes: 0
Reputation: 801
there's no 1 line css way to centered div vertically, so you need a workaround, try this simplest one.
body {
position:relative;
}
div {
position:absolute;
top: 50%;
}
with jquery
$(document).ready(function(){
$('div').css('margin-top', -$(this).height()/2);
});
note: the margin top of the div should be minus half of its height, so in this example, its -50px because its height is 100px.
Upvotes: 0
Reputation: 1236
You can use display: table-cell
and vertical-align: middle
to achieve this.
HTML:
<div class="container">
<div class="content">
blah blah
</div>
</div>
CSS:
.container {
display: table-cell;
height: 100vh;
text-align: center;
vertical-align: middle;
width: 100vw;
}
.content {
display: inline-block;
}
Here's a fiddle.
Upvotes: 1
Reputation: 125531
The flexbox way:
FIDDLE (Resize browser window))
<div class="container">
<div class="child"></div>
</div>
.container {
width: 80vw;
height: 80vh;
display:flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
background: aqua;
}
.child {
width: 50%;
height: 50%;
background: crimson;
}
Upvotes: 1
Reputation: 13998
There are definitely a lot of way you can achieve this. Here is one of the way. I am using position:absolute
.
.center
{
position: absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
border:5px solid black;
width:100px;
height:100px;
}
Upvotes: 1