我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。
<body>
<div>Div to be aligned vertically</div>
</body>
如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?
我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。
<body>
<div>Div to be aligned vertically</div>
</body>
如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?
当前回答
对于新手,请尝试:
display: flex;
align-items: center;
justify-content: center;
其他回答
这是迄今为止最简单的方法,也适用于非阻塞元素。唯一的缺点是它是Flexbox,因此,较旧的浏览器将不支持此功能。
<div class="sweet-overlay">
<img class="centered" src="http://jimpunk.com/Loading/loading83.gif" />
</div>
指向CodePen的链接:
http://codepen.io/damianocel/pen/LNOdRp
这里重要的一点是,对于垂直居中,我们需要定义父元素(容器),并且img的高度必须小于父元素。
只需这样做:在div中添加类:
.modal {
margin: auto;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
height: 240px;
}
请阅读本文以获得解释。注:高度是必需的。
名单上还有一个我看不到的:
.Center-Container {
position: relative;
height: 100%;
}
.Absolute-Center {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
border: solid black;
}
跨浏览器(包括Internet Explorer 8-Internet Explorer 10,无黑客攻击!)响应百分比和最小值/最大值-居中,不考虑填充(不考虑框大小!)必须声明高度(请参见可变高度)建议设置溢出:自动防止内容溢出(请参阅溢出)
来源:CSS中的绝对水平和垂直居中
将元素垂直居中的现代方法是使用flexbox。
你需要父母来决定身高,孩子来居中。
下面的示例将使div在浏览器中居中。重要的是(在我的示例中)将height:100%设置为body和html,然后将min-height:100%设置到容器。
正文,html{背景:#F5F5F5;框大小调整:边框框;高度:100%;边距:0;}#中心容器{对齐项目:居中;显示:柔性;最小高度:100%;}#中心{背景:白色;边距:0自动;填充:10px;文本对齐:居中;宽度:200px;}<div id='center_container'>我是中心</分区></div>
当我不得不回到这个问题上时,这总是我要去的地方。
对于那些不想跳的人:
将父容器指定为位置:相对或位置:绝对。指定子容器上的固定高度。在子容器上设置位置:绝对和顶部:50%,以将顶部向下移动到父容器的中间。设置页边距上限:-yy,其中yy是子容器高度的一半,以向上偏移项目。
代码中的示例:
<style type="text/css">
#myoutercontainer {position:relative}
#myinnercontainer {position:absolute; top:50%; height:10em; margin-top:-5em}
</style>
...
<div id="myoutercontainer">
<div id="myinnercontainer">
<p>Hey look! I'm vertically centered!</p>
<p>How sweet is this?!</p>
</div>
</div>