Vertically align text next to an image?

2018-12-31 00:29发布

Why won't vertical-align: middle work? And yet, vertical-align: top does work.

<div>
   <img style="width:30px;height:30px">
   <span style="vertical-align:middle">Doesn't work.</span>
</div>

20条回答
初与友歌
2楼-- · 2018-12-31 00:39

Change your div into a flex container:

div {display:flex;}


Now there are two methods to center the alignments for all the content:

Method 1:

div {align-items:center;}

DEMO


Method 2:

div * {margin-top:auto; margin-bottom:auto;}

DEMO


Try different width and height values on the img and different font size values on the span and you'll see they always remain in the middle of the container.

查看更多
无与为乐者.
3楼-- · 2018-12-31 00:39

Firstly inline CSS is not recommended at all, it really mess up your HTML.

For aligning image and span, you can simply do vertical-align:middle.

.align-middle {
  vertical-align: middle;
}
<div>
  <img class="align-middle" src="https://i.stack.imgur.com/ymxaR.png">
  <span class="align-middle">I'm in the middle of the image! thanks to CSS! hooray!</span>
</div>

查看更多
春风洒进眼中
4楼-- · 2018-12-31 00:40

Multiline solution:

http://jsfiddle.net/zH58L/6/

<div style="display:table;width:30px;height:160px;">
    <img style="display:table-cell;width:30px;height:60px;padding:50px" src='...' />
    <div style="display:table-cell;height:30px;vertical-align:middle">
      Multiline text centered vertically
    </div>
</div>
<!-- note: img (height + 2x padding) must be equal to root div height -->

Works in all browers and ie9+

查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 00:41

For the record, alignment "commands" shouldn't work on a SPAN, because it is an in-line tag, not a block-level tag. Things like alignment, margin, padding, etc won't work on an in-line tag because the point of inline is not to disrupt the text flow.

CSS divides HTML tags up into two groups: in-line and block-level. Search "css block vs inline" and a great article shows up...

http://www.webdesignfromscratch.com/html-css/css-block-and-inline/

(Understanding core CSS principles is a key to it not being quite so annoying)

查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 00:43

Because you have to set the line-height to the height of the div for this to work

查看更多
何处买醉
7楼-- · 2018-12-31 00:44

Basically, you'll have to get down to CSS3.

-moz-box-align: center;
-webkit-box-align: center;
查看更多
登录 后发表回答