简体   繁体   中英

How do I align a div container both vertically and horizontally on a page using CSS or CSS + jquery?

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...

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;
} 

DEMO

The flexbox way:

FIDDLE (Resize browser window))

Markup

<div class="container">
    <div class="child"></div>
</div>

CSS

.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;
}

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM