What is the best and easiest way to vertically center text that's next to an image in html? Needs to be browser version/type agnostic. A pure html/CSS solution.
We need to create a parent element that contain both image and text. After declaring the parent element as flexbox using display: flex; we can align the items to the center using align-items: center;. Example: This example uses flexbox to vertically align text next to an image using CSS.
To center an image using text-align: center; you must place the <img> inside of a block-level element such as a div . Since the text-align property only applies to block-level elements, you place text-align: center; on the wrapping block-level element to achieve a horizontally centered <img> .
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
In this case you can use display:inline or inline-block.
This might get you started.
I always fall back on this solution. Not too hack-ish and gets the job done.
EDIT: I should point out that you might achieve the effect you want with the following code (forgive the inline styles; they should be in a separate sheet). It seems that the default alignment on an image (baseline) will cause the text to align to the baseline; setting that to middle gets things to render nicely, at least in FireFox 3.
<div> <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg" style="vertical-align: middle;" width="100px"/> <span style="vertical-align: middle;">Here is some text.</span> </div>
Does "pure HTML/CSS" exclude the use of tables? Because they will easily do what you want:
<table> <tr> <td valign="top"><img src="myImage.jpg" alt="" /></td> <td valign="middle">This is my text!</td> </tr> </table>
Flame me all you like, but that works (and works in old, janky browsers).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With