原文出处:http://blog.sina.com.cn/s/blog_8d322eff010192wx.html
回答:设置容器的浮动方式为相对定位
然后确定容器的宽高 比如宽500 高 300 的层然后设置层的外边距
- <!DOCTYPE HTML>
- <html>
- <head>
- <style type="text/css">
- div{
- width: 500px;
- height: 300px;
- margin: -150px 0 0 -250px;
- position: absolute;
- left: 50%;
- top: 50%;
- background-color: yellow;
- }
- </style>
- </head>
- <body>
- <div>
- 元素居中
- </div>
- </body>
- </html>
<style type="text/css">
<!-- div { position:absolute; top:50%; left:50%; margin:-150px 0 0 -200px; width:400px; height:300px; border:1px solid #008800; } --> </style> <div>让层垂直居中于浏览器窗口</div> 其实解决的思路是这样的:首们需要position:absolute;绝对定位。而层的定位点,使用外补丁margin负值的方法。负值的大小为层自身宽度高度除以二。 如:一个层宽度是400,高度是300。使用绝对定位距离上部与左部都设置成50%。而margin-top的值为-150。<a target=_blank target="_blank" class="inner-link decor-none" href="http://zhidao.baidu.com/search?word=margin-left&fr=qb_search_exp&ie=utf8" rel="nofollow" style="color: rgb(45, 100, 179); text-decoration: none;">margin-left</a>的值为-200。这样我们就实现了层垂直居中于浏览器的样式编写 如果你是想让div垂直居中与div,那么你可以在父级div上加一个position:relative即可