Vertically align ::before/::after elements to parent, where parent needs to follow inline baseline
You can see in the attached image how the flag before the username is not vertical-centrally aligned to the username. The username is an anchor tag with a ::before rendering the famfamfam flag png.
The problem: when I set the anchor to:
... it will work for both the flag and username. However the username's baseline will then no longer adhere to the baseline of the inline flowing text it is part of.
What is the correct way to do this?
I've been playing with position: absolute; on the ::before, but it's messy and needs hacks to fix the (then missing) clearance of the flag image.
Thanks for any help π
![No description](https://cdn.answeroverflow.com/1147907773422645328/image.png)
7 Replies
You can use vertical-align:baseline; on the image. It will get you very close to center. It's actually closer than using vertical-align:middle, because the text descender is included in the calculations for centering, and your text doesn't have anything going below the baseline.
Thanks for responding:
- What is a text descender?
- Does the vertical-align property have effect when the parent's display mode is set to flex? (I shall try it out)
- Is there really no way to get both dead centre, and still maintain the intended parent baseline?
A descender is the part of a character that goes below the baseline. For example, the lower case letters "g,p,q" have descenders.
The vertical-align should not be used in combination with display:flex.
It is possible to get exact center, but you have to figure out the correct margin to make that happen. The vertical-align:middle actually does get you exact center, but it's the center including the descender, which looks wrong with text that doesn't go below the baseline.
Thank you. That makes sense. And it makes me sad this should be so hard....
It seems when using flex or grid to center vertically, the descender is accounted for. For me this makes sense as it's visually more coherent, which is why I'd like to use those display modes.
But yeah then the baseline of the paragraph text is lost.
I cannot use margins as the images will vary in height in other cases.
I realize that. That is why I did not recommend it in the beginning. I was only mentioning that in response to your question about a way to get exact centering. Margin will work but you will need a different margin for each image. The vertical-align approach is more automatic.
margin: auto; only works horizontally and not vertically, right?
In most cases, this is true. There are some special exceptions when used in combination with position:absolute and inset.