我有一个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.ext-box{显示:表;宽度:100%;} Div.int-box{显示:表单元;vertical-align:中间;} < div class = " ext-box”> < div class = " int-box”> 一些txt < h2 > < / h2 > <p>bla bla bla</p> < / div > < / div >
显然,无论您使用.class还是#id,结果都不会改变。
其他回答
<div id="header" style="display: table-cell; vertical-align:middle;">
...
或CSS
.someClass
{
display: table-cell;
vertical-align:middle;
}
浏览器覆盖
默认情况下,h1是一个块元素,将在第一个img之后的行上呈现,并将导致第二个img出现在块之后的行上。
为了阻止这种情况发生,你可以将h1设置为内联流行为:
#header > h1 { display: inline; }
至于绝对定位img在div中,你需要设置包含div的“已知大小”,这样才能正常工作。在我的经验,你还需要改变位置属性从默认位置:相对工作为我:
#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }
如果你能让它工作,你可能想尝试逐步从div.header中删除高度、宽度、位置属性,以获得获得你想要的效果所需的最小属性。
更新:
下面是一个在Firefox 3上运行的完整示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Example of vertical positioning inside a div</title> <style type="text/css"> #header > h1 { display: inline; } #header { border: solid 1px red; position: relative; } #img-for-abs-positioning { position: absolute; bottom: -1em; right: 2em; } </style> </head> <body> <div id="header"> <img src="#" alt="Image 1" width="40" height="40" /> <h1>Header</h1> <img src="#" alt="Image 2" width="40" height="40" id="img-for-abs-positioning" /> </div> </body> </html>
垂直和水平对齐元素
使用它们中的任何一个。结果是一样的:
引导4 CSS3
1. 引导4.3 +
垂直对齐:d-flex align-items-center
水平对齐:d-flex justify-content-center
垂直和水平对齐:d-flex align-items-center justify-content-center
.container { 身高:180 px; 宽度:100%; background - color: blueviolet; } .container > div { 背景颜色:白色; 填充:1快速眼动; } <链接的href = " https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css " rel = "样式表" / > <div class="d-flex align-items-center - align- content-center container"> <div>我在中心</div> < / div >
2. CSS 3
.container { 身高:180 px; 宽度:100%; background - color: blueviolet; } .container > div { 背景颜色:白色; 填充:1快速眼动; } .center { 显示:flex; 对齐项目:中心; justify-content:中心; } <div class="集装箱中心"> <div>我在中心</div> < / div >
就在这个:
<div>
<table style="width: 100%; height: 100%">
<tr>
<td style="width: 100%; height: 100%; vertical-align: middle;">
What ever you want vertically-aligned
</td>
</tr>
</table>
</div>
一个单元表内的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%;
}
根据我的理解,包含元素的文本的直接父元素必须有一定的高度。