Why won't vertical-align: middle
work? And yet, vertical-align: top
does work.
<div>
<img style="width:30px;height:30px">
<span style="vertical-align:middle">Doesn't work.</span>
</div>
Why won't vertical-align: middle
work? And yet, vertical-align: top
does work.
<div>
<img style="width:30px;height:30px">
<span style="vertical-align:middle">Doesn't work.</span>
</div>
Here are some simple techniques for vertical-align:
One-line vertical-align:middle
This one is easy: set the line-height of the text element to equal that of the container
Multiple-lines vertical-align:bottom
Absolutely position an inner div relative to its container
Multiple-lines vertical-align:middle
If you must support ancient versions of IE <= 7
In order to get this to work correctly across the board, you'll have to hack the CSS a bit. Luckily, there is an IE bug that works in our favor. Setting
top:50%
on the container andtop:-50%
on the inner div, you can achieve the same result. We can combine the two using another feature 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, as it makes use of the
transform: translateY
property. (http://caniuse.com/#feat=transforms2d)Applying the following 3 lines of CSS to an element will vertically centre it within its parent regardless of the height of the parent element:
This code works in IE as well as FF:
Haven't seen a solution with
margin
in any of these answers yet, so here is my solution to this problem.This solution only works if you know the width of your image.
The HTML
The CSS
Use
line-height:30px
for the span so that text is align with the image:It can be confusing, I agree. Try utilizing table features. I use this simple CSS trick to position modals at the center of the webpage. It has large browser support:
and CSS part:
Note that you have to style and adjust the size of image and table container to make it work as you desire. Enjoy.
Another thing you can do is set the text's
line-height
to the size of the images within the<div>
. Then set the images tovertical-align: middle;
That's seriously the easiest way.