CSS 垂直对齐块元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22109450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:00:42  来源:igfitidea点击:

Vertical-Align a Block Element

cssvertical-alignment

提问by Jaeeun Lee

I have an image and text next to each other in a div. I'm trying to align the text vertically aligned in the middle, but it stays on top. Please help!

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

http://jsfiddle.net/9KDva/

http://jsfiddle.net/9KDva/

HTML:

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:

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;
}

采纳答案by JunM

You can use tableand table-cell: And move your class='title'inside img-holder

您可以使用tableand table-cell:并移动您的class='title'内部img-holder

Fiddle

小提琴

With padding left away from image- fiddle

填充远离image-小提琴

.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;  
}

回答by jellyfication

I changed your div to span for vertical-align: middleto work.

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

See Fiddle: http://jsfiddle.net/9KDva/4/

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

CSS:

CSS:

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

HTML:

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>

回答by Suchan Lee

Using vertical-align: middle won't work on a div.

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

Something like this might work:

像这样的事情可能会奏效:

<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>