我试图获得一个响应大小的图像和一个h2标题在中间(垂直)对齐,但我迷路了。它是页面顶部的标题。
图像是大约的图像。 100 x 100像素(但可能会因使用的图像而异),但在窗口较小时(平板电脑,手机)需要将页面容器宽度的最大值调整为最大值的15%。
因为图像的高度将大于标题的高度,所以我希望将h2与图像垂直对齐。当窗口变小时,图像将缩小。即使h2的高度大于图像(非常大的标题),h2也应该在中心对齐
这是我的HTML(这是针对新的消息页面,但我将在各种页面上使用它)
<div class="header_image clearfix">
<img src="message_new.png" />
<h2>Write new message</h2>
</div>
这是它的CSS:
.header_image {
position: relative;
}
.header_image img {
max-width: 15%;
float: left;
}
.header_image h2 {
vertical-align: middle;
}
.clearfix:before,
.clearfix:after {
display: table;
content: " ";
}
我已经尝试使用display:table作为父DIV并显示:table-cell表示img和h2(并删除了图像上的浮点数)。 不幸的是,当使用table-cell时,max-width选项不再对图像起作用,因为图像将调整为表格单元格的15%,而不是表格的15%。
有谁知道如何做这个css?
谢谢,巴里
答案 0 :(得分:2)
尝试使用display:inline-block
代替float
<强> CSS 强>
.header_image {
position: relative;
}
.header_image img {
max-width: 15%;
display: inline-block;
vertical-align: middle;
}
.header_image h2 {
display: inline-block;
vertical-align: middle;
max-width:80%; /* in case of longer text */
}
答案 1 :(得分:1)
You can use this also
.header_image {
position: relative;
}
.header_image img {
max-width: 15%;
display:inline-block;
}
.header_image h2 {
display:inline-block;
max-width:80%;
}