Div horizontally center and vertically middle [dup

2019-03-18 06:04发布

问题:

This question already has an answer here:

  • Best way to center a <div> on a page vertically and horizontally? [duplicate] 30 answers

I want to align a div horizontally center and vertically middle of the body of a page.

The css:

.loginBody {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    background: #999; /* for non-css3 browsers */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); /* for IE */
    background: -webkit-gradient(linear, left top, left bottom, from(#ccc), to(#000)); /* for webkit browsers */
    background: -moz-linear-gradient(top,  #ccc,  #000); /* for firefox 3.6+ */
}
.loginDiv {
    position: absolute;
    left: 35%;
    top: 35%;
    text-align: center;        
    background-image: url('Images/loginBox.png');
    width:546px;
    height:265px;
}

And I have this html:

<body class="loginBody">
    <form id="form1">
    <div class="loginDiv">

    </div>
    </form>
</body>

Now it is behaving as I want it to, but if I resize the browser, it became completely distorted, perhaps this is because the absolute positioning. I am showing some of the screenshots: in resized firefox:

in resized chrome:

in resized ie:

in maximized window it is:

Is there any way to solve this problem and achieve this centered alignment using relative positioning?

Thanks.


Edit:

In firefox no scrollbar appears while resizing but it appears in other browsers.

回答1:

Try this:

.loginDiv {
    position: absolute;
    left: 50%;
    top: 50%;
    text-align: center;        
    background-image: url('Images/loginBox.png');
    width:546px;
    height:265px;
    margin-left: -273px; /*half width*/
    margin-top: -132px; /*half height*/
}

You move it to the center, and than back left and up by half the dimensions - that will center it even on resize



回答2:

Make a div that is for the content of the page and make a "content" class with the following css. This worked for me on Jquery Mobile with Phonegap for Android devices. Hope it helps someone.

CSS

.content {

        width: 100%;
        height: 100%;
        top: 25%;
        left: 25%
        right: 25%;
        text-align: center;
        position: fixed;
}


回答3:

#div {
    height: 200px;
    width: 100px;
    position:absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -50px;
}

This is a common method to center a div. You position it absolutely, then move it half way across and half way down. Then adjust the position with margins by half the dimensions of the div you are positioning.

For reference (this uses fixed positioning though to keep the div in place even when scrolling, helpful when doing modal popups.. http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/