我有一个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>
当前回答
我最喜欢的新方法是用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>
其他回答
我一个朋友的一个技巧:
Div:前面{内容:" ";显示:inline-block;高度:100%;vertical-align:中间;} Div p{显示:inline-block;} < div风格= "高度:100 px;边界:1 px固体;" > < span style=" font - family:宋体;"</p> .我是垂直居中的 < / div >
演示。
要将块元素定位到中心(适用于Internet Explorer 9及以上版本),它需要一个包装器div:
.vcontainer {
position: relative;
top: 50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
所有这些都需要在div中垂直对齐
对齐的如何?图片的顶部与文字的顶部对齐?
其中一个图像需要在div中绝对定位。
相对于DIV的绝对定位?也许你可以把你要找的东西画出来?
fd描述了绝对定位的步骤,以及调整H1元素的显示,以便图像将与它内联显示。除此之外,我还要补充一点,你可以使用vertical-align样式来对齐图像:
#header h1 { display: inline; }
#header img { vertical-align: middle; }
...这将把标题和图像放在一起,顶部边缘对齐。还有其他对齐选项;请参见文档。你可能还会发现删除DIV并将图像移动到H1元素内部是有益的——这为容器提供了语义值,并消除了调整H1显示的需要:
<h1 id=header">
<img src=".." ></img>
testing...
<img src="..."></img>
</h1>
默认情况下,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>
这招对我很管用:
.vcontainer {
min-height: 10em;
display: table-cell;
vertical-align: middle;
}