我有一个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>
当前回答
几乎所有的方法都需要指定高度,但通常我们没有任何高度。
这里有一个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
其他回答
几乎所有的方法都需要指定高度,但通常我们没有任何高度。
这里有一个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:前面{内容:" ";显示:inline-block;高度:100%;vertical-align:中间;} Div p{显示:inline-block;} < div风格= "高度:100 px;边界:1 px固体;" > < span style=" font - family:宋体;"</p> .我是垂直居中的 < / 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>
这是我个人的解决方案的i元素在一个div。
JSFiddle例子
HTML
<div class="circle">
<i class="fa fa-plus icon">
</i></div>
CSS
.circle {
border-radius: 50%;
color: blue;
background-color: red;
height:100px;
width:100px;
text-align: center;
line-height: 100px;
}
.icon {
font-size: 50px;
vertical-align: middle;
}
对我来说,它是这样工作的:
<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”。