How to put a div in center of browser using CSS?

2019-01-21 16:19发布

How to put a div in center of browser both vertically and horizontally using CSS only?

Make sure it works on IE7 too.

If everything fails, we may use JavaScript, but a last choice.

标签: css layout
9条回答
放荡不羁爱自由
2楼-- · 2019-01-21 16:58
<html>
<head>
<style>
*
{
    margin:0;
    padding:0;
}

html, body
{
    height:100%;
}

#distance
{
    width:1px;
    height:50%;
    margin-bottom:-300px;
    float:left;
}


#something
{
    position:relative;
    margin:0 auto;
    text-align:left;
    clear:left;
    width:800px;
    min-height:600px;
    height:auto;
    border: solid 1px #993333;
    z-index: 0;
}

/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>

</head>
<body>

<div id="distance"></div>

<div id="something">
</div>
</body>

</html>

Tested in FF2-3, IE6-7, Opera and works well!

查看更多
Rolldiameter
3楼-- · 2019-01-21 17:04

The simplest solution is just to use an auto margin, and give your div a fixed width and height. This will work in IE7, FF, Opera, Safari, and Chrome:

HTML:

<body>
  <div class="centered">...</div>
</body>

CSS:

body { width: 100%; height: 100%; margin: 0px; padding: 0px; }

.centered
{
    margin: auto;
    width: 400px;
    height: 200px;
}

EDIT!! Sorry, I just noticed you said vertically...the default "auto" margin for top and bottom is zero...so this will only center it horizontally. The only solution to position vertically and horizontally is to muck around with negative margins like the accepted answer.

查看更多
做个烂人
4楼-- · 2019-01-21 17:04
.center {
  margin: auto;
  margin-top: 15vh;
}

Should do the trick

查看更多
登录 后发表回答