我想用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,未知解决方案中的居中对我来说非常有用。
它在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>
其他回答
我这样做了(相应地改变宽度、高度、顶部边距和左侧边距):
.wrapper {
width: 960px;
height: 590px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -295px;
margin-left: -480px;
}
<div class="wrapper"> -- Content -- </div>
.center{
display: grid;
place-items: center;
}
当我不得不回到这个问题上时,这总是我要去的地方。
对于那些不想跳的人:
将父容器指定为位置:相对或位置:绝对。指定子容器上的固定高度。在子容器上设置位置:绝对和顶部: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>
我觉得这个最有用。。。它给出了最准确的“H”布局,并且非常容易理解。
这种标记的好处是您可以在一个地方定义内容大小->“PageContent”。
页面背景的颜色及其水平边距在其相应的div中定义。
<div id="PageLayoutConfiguration"
style="display: table;
position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
width: 100%; height: 100%;">
<div id="PageBackground"
style="display: table-cell; vertical-align: middle;
background-color: purple;">
<div id="PageHorizontalMargins"
style="width: 100%;
background-color: seashell;">
<div id="PageContent"
style="width: 1200px; height: 620px; margin: 0 auto;
background-color: grey;">
My content goes here...
</div>
</div>
</div>
</div>
这里用CSS分隔:
<div id="PageLayoutConfiguration">
<div id="PageBackground">
<div id="PageHorizontalMargins">
<div id="PageContent">
my content goes here...
</div>
</div>
</div>
</div>
#PageLayoutConfiguration{
display: table;
width: 100%;
height: 100%;
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#PageBackground{
display: table-cell;
vertical-align: middle;
background-color: purple;
}
#PageHorizontalMargins{
width: 100%;
background-color: seashell;
}
#PageContent{
width: 1200px;
height: 620px;
margin: 0 auto;
background-color: grey;
}
我只是找到了另一种对我有用的方法:
<div class="container">
<div class="vertical">
<h1>Welcome</h1>
<h2>Aligned Vertically</h2>
<a href="#">Click ME</a>
</div>
</div>
CSS
.vertical{
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
更多信息