我想用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?
当前回答
因为每次我需要垂直居中div时,我都会一遍又一遍地搜索它,这个答案总是首先出现的,所以我会把这个留给未来的我(因为提供的解决方案都不能很好地满足我的需求):
因此,如果已经在使用引导程序,可以按如下方式进行:
<div style="min-height: 100vh;" class="align-items-center row">
<div class="col" style="margin: auto; max-width: 750px;"> //optional style to center horizontally as well
//content goes here
</div>
</div>
其他回答
最好的做法是:
#vertalign{
height: 300px;
width: 300px;
position: absolute;
top: calc(50vh - 150px);
}
150像素,因为在本例中,这是div高度的一半。
不回答浏览器兼容性,但也要提到新的网格和不那么新的Flexbox功能。
Grid
来自:Mozilla-网格文档-垂直对齐Div
浏览器支持:网格浏览器支持
CSS:
.wrapper {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
grid-auto-rows: 200px;
grid-template-areas:
". a a ."
". a a .";
}
.item1 {
grid-area: a;
align-self: center;
justify-self: center;
}
HTML格式:
<div class="wrapper">
<div class="item1">Item 1</div>
</div>
柔性包装箱
浏览器支持:Flexbox浏览器支持
CSS:
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;
特别是对于具有相对(未知)高度的父div,未知解决方案中的居中对我来说非常有用。
它在Chrome、Firefox、Opera和Internet Explorer中进行了测试。
/*此父项可以是任何宽度和高度*/.块{文本对齐:居中;}/*鬼魂被推着保持完美的居中*/.block:之前{内容:“”;显示:内联块;高度:100%;垂直对齐:中间;右边距:-0.25em;/*调整间距*/}/*要居中的元素可以也可以是任何宽度和高度*/.居中{显示:内联块;垂直对齐:中间;宽度:300px;}<div style=“width:400px;height:200px;”><div class=“block”style=“高度:90%;宽度:100%”><div class=“center”><h1>一些文本</h1><p>任何其他文本。。。“”</p></div></div></div>
因为每次我需要垂直居中div时,我都会一遍又一遍地搜索它,这个答案总是首先出现的,所以我会把这个留给未来的我(因为提供的解决方案都不能很好地满足我的需求):
因此,如果已经在使用引导程序,可以按如下方式进行:
<div style="min-height: 100vh;" class="align-items-center row">
<div class="col" style="margin: auto; max-width: 750px;"> //optional style to center horizontally as well
//content goes here
</div>
</div>
这在我的情况下有效(仅在现代浏览器中测试):
.textthatneedstobecentered {
margin: auto;
top: 0; bottom: 0;
}