[英]What is the easiest method for vertical+horizontal centering of a div in the window?
给定已知尺寸的div
,例如width: 300px; height: 200px
width: 300px; height: 200px
,最简单的方法是将它垂直和水平放置在屏幕中间? 这里的例子
我对最新的Firefox感兴趣(不需要IE黑客)。
只有CSS,没有Javascript。
将它从窗口/父容器中定位50%,并使用负边距大小为元素宽度/高度的一半:)
position: absolute; // or fixed if you don't want it scrolling with the page.
width: 300px;
height: 200px;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -100px;
您可能需要在body
和html
上设置height: 100%
html, body {
height: 100%;
}
编辑:这是一个有效的例子 。
在不支持IE的情况下,使用display: table
和display: table-cell
实际上很容易实现。
这是对HTML的更新:
<div id='my_div'>
<div class="centered">this is vertically centered</div>
</div>
CSS:
body, html
{
height: 100%;
}
body
{
margin: 0;
padding: 0;
border: 1px solid blue;
}
#my_div
{
width: 300px;
border: 1px solid red;
margin-left: auto;
margin-right: auto;
height: 100%;
display: table;
overflow: hidden;
}
.centered
{
display: table-cell;
vertical-align: middle;
text-align: center;
}
并预览: http : //jsfiddle.net/we8BE/
我不知道这是否是最简单的方法,但似乎有效。
http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm
你有什么方法可以使用? 例如CSS到什么级别 - 2或3? JavaScript的? jQuery的? 我的第一个想法是,因为div可以通过margin-left: auto;
水平居中margin-left: auto;
和margin-right: auto;
,也许尝试margin: auto;
对于所有4个方面。 如果有效,请告诉我。
最简单的? 众多jQuery中心插件之一......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.