我有一个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>
当前回答
只使用Bootstrap类:
Div: class="容器d-flex" div中的元素:class="m-auto"
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" crossorigin="anonymous"> < span class=" font - family:宋体" style=" font - family:宋体;background - color: # 333;" > < h2 class = " m-auto " > < a href = " https://hovermind.com/ " > H➲版本➾M⇡ND < / > < / h2 > < / div >
其他回答
只需在div中使用一个单格表!只需设置单元格和表格的高度和与100%,你可以使用垂直对齐。
一个单元表内的div处理垂直对齐和向后兼容回石器时代!
我一个朋友的一个技巧:
Div:前面{内容:" ";显示:inline-block;高度:100%;vertical-align:中间;} Div p{显示:inline-block;} < div风格= "高度:100 px;边界:1 px固体;" > < span style=" font - family:宋体;"</p> .我是垂直居中的 < / div >
演示。
下面是另一种(响应性的)方法:
html,
body {
height: 100%;
}
body {
margin: 0;
}
.table {
display: table;
width: auto;
table-layout:auto;
height: 100%;
}
.table:nth-child(even) {
background: #a9edc3;
}
.table:nth-child(odd) {
background: #eda9ce;
}
.tr {
display: table-row;
}
.td {
display: table-cell;
width: 50%;
vertical-align: middle;
}
http://jsfiddle.net/herrfischerhamburg/JcVxz/
哇,这个问题很受欢迎。这是基于对垂直对齐属性的误解。这篇优秀的文章解释了这一点:
理解垂直对齐,或者Gavin Kistner的“如何(不)垂直居中内容”。
“如何在CSS中居中”是一个很好的网络工具,它可以帮助您在不同的情况下找到必要的CSS居中属性。
简而言之(并防止链接腐烂):
Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example For block elements, vertical alignment is harder and strongly depends on the specific situation: If the inner element can have a fixed height, you can make its position absolute and specify its height, margin-top and top position. jsfiddle example If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example … there are more such special cases.
几乎所有的方法都需要指定高度,但通常我们没有任何高度。
这里有一个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