how to vertically align text next to a floated ima

2019-02-05 20:53发布

I want to vertically align a span after a floated image. I searched for it in stack overflow and find this post. but my image is floated.

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

I give vertical-align:middle to image and nothing change!

Thanks

6条回答
Bombasti
2楼-- · 2019-02-05 21:20

First remove float from it. Write like this:

<img style="width:30px;height:30px;vertical-align:middle" src="http://lorempixel.com/output/abstract-q-c-640-480-8.jpg">
    <span>Doesn't work.</span>

Check this http://jsfiddle.net/ws3Uf/

查看更多
爷、活的狠高调
3楼-- · 2019-02-05 21:25

A <span> is an inline element, try adding display:block to the span, give it the same height as the image and a line height to match. Float it left as well. That should work

查看更多
爷的心禁止访问
4楼-- · 2019-02-05 21:25

You could do the following:

  div:after {
        content:"";
        clear:both;
        display:block;
    }
查看更多
ら.Afraid
5楼-- · 2019-02-05 21:31

You can manually change as well

<div>
    <img style="width:30px;height:30px float:left">
    <span style="float:left;padding-top:15px;">Will work.</span>
</div>

Demo

Or you can use a table

查看更多
我命由我不由天
6楼-- · 2019-02-05 21:39

Even though this is an extremely old post, you can achieve this using Flexbox:

div {
 display: flex;
 align-items: center;
}
<div>
<img style="width:30px;height:30px;" src="http://lorempixel.com/output/abstract-q-c-640-480-8.jpg" />
<span>Doesn't work.</span>
</div>

JsFiddle example

查看更多
冷血范
7楼-- · 2019-02-05 21:42

Add line-height (equal to picture height):

<div>
    <img style="width:30px;height:30px; float:left">
    <span style="vertical-align:middle; line-height: 30px;">Works!</span>
</div>

See example.

查看更多
登录 后发表回答