我想用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?
当前回答
.center{
display: grid;
place-items: center;
}
其他回答
实际上,垂直居中需要两个div。包含内容的div必须具有宽度和高度。
#集装箱{位置:绝对;顶部:50%;页边空白:-200像素;/*#内容高度的一半*/左:0;宽度:100%;}#内容{宽度:624px;左边距:自动;右边距:自动;高度:395px;边框:1px实心#000000;}<div id=“container”><div id=“content”><h1>居中的div</h1></div></div>
这是结果。
名单上还有一个我看不到的:
.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中的绝对水平和垂直居中
可以通过两种方式实现
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;
}
对齐项目:居中;使内容垂直居中
对齐内容:中心;使内容水平居中
最好的做法是:
#vertalign{
height: 300px;
width: 300px;
position: absolute;
top: calc(50vh - 150px);
}
150像素,因为在本例中,这是div高度的一半。
Billbad的答案只适用于固定宽度的.intern除法。此解决方案通过将属性textalign:center添加到.outer div中来实现动态宽度。
.外部{位置:绝对;显示:表格;宽度:100%;高度:100%;文本对齐:居中;}.中间{显示:表格单元格;垂直对齐:中间;}.内部{文本对齐:居中;显示:内联块;宽度:自动;}<div class=“outer”><div class=“middle”><div class=“inner”>所容纳之物</div></div></div>