我想用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?
当前回答
可以通过两种方式实现
body{
left: 50%;
top:50%;
transform: translate(-50%, -50%);
height: 100%;
width: 100%;
}
OR
使用flex
body {
height:100%
width:100%
display: flex;
justify-content: center;
align-items: center;
}
对齐项目:居中;使内容垂直居中
对齐内容:中心;使内容水平居中
其他回答
CSS网格
正文,html{margin:0;}正文{显示:栅格;最小高度:100vh;对齐项目:居中;}<div>div垂直对齐</div>
我刚刚写了这篇CSS,想了解更多信息,请浏览:这篇文章用3行CSS垂直对齐任何内容。
.element {
position: relative;
top: 50%;
transform: perspective(1px) translateY(-50%);
}
当我不得不回到这个问题上时,这总是我要去的地方。
对于那些不想跳的人:
将父容器指定为位置:相对或位置:绝对。指定子容器上的固定高度。在子容器上设置位置:绝对和顶部: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>
声明此Mixin:
@mixin vertical-align($position: relative) {
position: $position;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
然后将其包含在元素中:
.element{
@include vertical-align();
}
这个解决方案适用于块元素(例如,<div>)。我用颜色使溶液更清晰。
HTML格式:
<main class="skin_orange">
<p>As you can the the element/box is vertically centered</p>
<div class="bigBox skin_blue">Blue Box</div>
</main>
CSS:
main {
position: relative;
width: 400px;
height: 400px;
}
.skin_orange {
outline: thin dotted red;
background: orange;
}
.bigBox {
width: 150px;
height: 150px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.skin_blue {
background-color: blue;
}
JSFiddle代码演示