【问题标题】:Responsive image middle aligned with a h2 header响应式图像中间与 h2 标题对齐
【发布时间】:2014-09-02 18:44:33
【问题描述】:

我试图让一个响应大小的图像和一个 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 和 display: table-cell 作为 img 和 h2 (并删除了图像上的浮动)。 不幸的是,当使用表格单元格时,最大宽度选项将不再对图像起作用,因为图像将调整为表格单元格的 15%,而不是表格的 15%。

有没有人知道怎么做css?

谢谢,巴里

【问题讨论】:

    标签: image css header


    【解决方案1】:

    尝试display:inline-block 而不是float

    JSfiddle

    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 行时,它应该分成 2 行(或更多行),图像在左侧,而不是顶部。
    • 只需向h2 添加一个最大宽度 - jsfiddle.net/9kmr2fp4/1 答案已更新。
    • 超级!那确实解决了它!
    • 谢谢...如果您愿意将此标记为答案,我们将不胜感激。
    【解决方案2】:
    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%;  
    
    }
    

    【讨论】:

    • 谢谢,这几乎同样有效,但它不能正确居中图像和 h2。对于大文本和小窗口,图像垂直居中在文本的中间,而不是父级。
    猜你喜欢
    • 2014-12-31
    • 2019-05-07
    • 2015-07-18
    • 1970-01-01
    • 2015-07-25
    • 2019-08-24
    • 2013-08-31
    • 2013-09-08
    • 1970-01-01
    相关资源
    最近更新 更多