How to vertically align text with image?
P粉360266095
2023-08-27 12:45:29
<p>为什么 <code>vertical-align: middle</code> 不起作用?然而, <code>vertical-align: top</code> <em>确实</em>有效。</p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">span{
vertical-align: middle;
}</pre>
<pre class="brush:html;toolbar:false;"><div>
<img src="https://via.placeholder.com/30" alt="small img" />
<span>Doesn't work.</span>
</div></pre>
<p><br /></p>
Here are some simple techniques for vertical alignment:
Single line vertical alignment: middle
This is simple: set the line height of the text element equal to the line height of the container
Multiple lines vertical-align:bottom
Absolutely position the inner div relative to its container
Multiple lines vertical-align:middle
If you must support older versions of IE
In order for this to fully work properly, you must make some modifications to the CSS. Luckily, there's an IE bug that works in our favor. Setting
top:50%
on the container andtop:-50%
on the inner div gives the same result. We can combine the two using another feature that IE doesn't support: advanced CSS selectors.Variable container height vertical-align:middle
This solution requires a slightly more modern browser than the other solutions because it uses the
transform:translateY
attribute. (http://caniuse.com/#feat=transforms2d)Applying the following 3 lines of CSS to an element will center it vertically within its parent element, regardless of the height of the parent element:
Actually, in this case, it's very simple: apply vertical alignment to the image. Since everything is on one line, you're actually aligning the image, not the text.