我有一个div与两个图像和一个h1。所有这些都需要在div中垂直对齐,彼此相邻。其中一个图像需要在div中绝对定位。
要在所有常见浏览器上工作,需要什么样的CSS ?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
我有一个div与两个图像和一个h1。所有这些都需要在div中垂直对齐,彼此相邻。其中一个图像需要在div中绝对定位。
要在所有常见浏览器上工作,需要什么样的CSS ?
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
当前回答
我发现了一个新的解决方案,垂直对齐多个文本行在一个div使用CSS 3(我也使用bootstrap v3网格系统来美化UI),如下所示:
.immediate-parent-of-text-containing-div {
height: 50px; /* Or any fixed height that suits you. */
}
.text-containing-div {
display: inline-grid;
align-items: center;
text-align: center;
height: 100%;
}
根据我的理解,包含元素的文本的直接父元素必须有一定的高度。
其他回答
<div id="header" style="display: table-cell; vertical-align:middle;">
...
或CSS
.someClass
{
display: table-cell;
vertical-align:middle;
}
浏览器覆盖
要将块元素定位到中心(适用于Internet Explorer 9及以上版本),它需要一个包装器div:
.vcontainer {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
几乎所有的方法都需要指定高度,但通常我们没有任何高度。
这里有一个css3的三行技巧,它不需要知道高度。
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
甚至在IE9中也支持它。
与其供应商前缀:
.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
来源:垂直对齐任何只需3行CSS
对我来说,它是这样工作的:
<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
<a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>
“a”元素转换为按钮,使用Bootstrap类,它现在垂直居中在一个外部的“div”。
我最喜欢的新方法是用CSS网格:
/* technique */ .wrapper { display: inline-grid; grid-auto-flow: column; align-items: center; justify-content: center; } /* visual emphasis */ .wrapper { border: 1px solid red; height: 180px; width: 400px; } img { width: 100px; height: 80px; background: #fafafa; } img:nth-child(2) { height: 120px; } <div class="wrapper"> <img src="https://source.unsplash.com/random/100x80/?bear"> <img src="https://source.unsplash.com/random/100x120/?lion"> <img src="https://source.unsplash.com/random/100x80/?tiger"> </div>