How to vertical-align to x-height?

2019-07-23 05:14发布

问题:

I have a line of text and a small image, which I am trying to align vertically within the line. My goal is to align the vertical center of the image with the x-height (or half of the height of a capital letter) from the baseline of the text. I can't figure out any way to do this. The closest thing that I know of is:

vertical-align: middle;

This behavior as it is stated in the CSS 2.1 spec:

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent

If there were a way to remove the world "half" from that definition, I'd have what I want. How do I accomplish this?

回答1:

The problem is, text sits on the text baseline while the image descends below that. And different browsers handle that differently.

My favorite solution is to display the image as a background-image, with its background-position set to left center ... you can season to taste.



回答2:

Don't know if it's the "best" answer, but I would always set the "line-height" of my text to match the height of what I'm trying to center it in.



回答3:

Here is the vertical align center.

http://www.templatespoint.com/blog/2010/10/div-vertical-align-middle/

or use image as background image

background:url(bg_image.jpg) no-repeat left center;