【问题标题】:Vertical-Align a Block Element垂直对齐块元素
【发布时间】:2025-11-10 23:00:02
【问题描述】:

我在 div 中有一个相邻的图像和文本。我正在尝试将文本垂直对齐在中间,但它保持在顶部。请帮忙!

http://jsfiddle.net/9KDva/

HTML:

<div class="title-block">
  <div class="img-holder"><img width="101" height="104" src="http://www.girlsguidetomanners.com/wp-content/uploads/2014/02/url-16-101x104.jpeg" class="attachment-homepoststhumbnail wp-post-image" alt="url-16" /></div>
  <div class="title">Get Your Nose Out of Your IPhone</div>
</div>

CSS:

.title-block {
width:272px;
height: 110px;
vertical-align:middle;
}

.img-holder {
float: left;
margin: 0 6px 0 0;
position: relative;
}

.img-holder img {
display: block;
}

.title {
display:block;
text-transform: uppercase;
margin: 8px 0 9px;
}

【问题讨论】:

标签: css vertical-alignment


【解决方案1】:

您可以使用tabletable-cell:并将您的class='title' 移动到img-holder

Fiddle

image 离开填充 - fiddle

.title-block {
    width:272px;
    height: 110px;    
}

.img-holder {    
    margin: 0 6px 0 0;
    position: relative;
    display: table;
}

img, .title{
    display:table-cell;
    vertical-align: middle;
}
.title {
    text-transform: uppercase;
    margin: 8px 0 9px;  
}

【讨论】:

    【解决方案2】:

    我将您的 div 更改为 span 以便 vertical-align: middle 工作。

    见小提琴:http://jsfiddle.net/9KDva/4/

    CSS:

    .vam {
        vertical-align: middle;
    }
    span.vam {
        display: inline-block;
    }
    

    HTML:

    <div class="title-block">
       <span class="img-holder vam">
    <img width="101" height="104" src="http://www.girlsguidetomanners.com/wp-content/uploads/2014/02/url-16-101x104.jpeg" class="attachment-homepoststhumbnail wp-post-image" alt="url-16" /></span>
        <span class="title vam">Get Your Nose Out of Your IPhone</span>
    
     </div>
    

    【讨论】:

      【解决方案3】:

      使用 vertical-align: middle 对 div 不起作用。

      这样的事情可能会奏效:

      <table class="title-block" style="background-image:url('http://www.girlsguidetomanners.com/wp-content/uploads/2014/02/url-16-101x104.jpeg); background-size: cover; background-position: center center;">
        <tr>
           <td class="title" style="vertical-align: middle;">
               Get Your Nose Out of Your IPhone
           </td>
        </tr>
      </table>
      

      【讨论】:

      • 表格应该用于表格内容,而不是布局!