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:41
margin: auto;
查看更多
放荡不羁爱自由
3楼-- · 2019-01-21 16:45

HTML:

<div id="something">... content ...</div>

CSS:

#something {
    position: absolute;
    height: 200px;
    width: 400px;
    margin: -100px 0 0 -200px;
    top: 50%;
    left: 50%;
}
查看更多
你好瞎i
4楼-- · 2019-01-21 16:49

For Older browsers, you need to add this line on top of HTML doc

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
查看更多
Animai°情兽
5楼-- · 2019-01-21 16:50

You can also set your div with the following:

#something {width: 400px; margin: auto;}

With that setting, the div will have a set width, and the margin and either side will automatically set depending on the with of the browser.

查看更多
神经病院院长
6楼-- · 2019-01-21 16:52

try this

#center_div
{
       margin: auto;
       position: absolute;
       top: 0; 
       left: 0;
       bottom: 0; 
       right: 0;
 }
查看更多
ら.Afraid
7楼-- · 2019-01-21 16:58

Using this:

center-div { margin: auto; position: absolute; top: 50%; left: 50%; bottom: 0; right: 0; transform: translate(-50% -50%); }
查看更多
登录 后发表回答