Align image and text in the middle of a button element

What will be the best and easiest way to align the text and image vertically in the middle of the button. Example:

button { padding: 1px 6px 1px 6px; } button img { width: 22px; height: 22px; } 
 <button> <img src="http://latvijas-universitates-matematikas-un-informatikas-instituts.atver.lv/images/msn-icon.gif" alt="Text" /> <span>Text</span> </button> 
+8
html css
source share
5 answers
 button{ padding: 5px 6px 5px 30px; background: url('http://latvijas-universitates-matematikas-un-informatikas-instituts.atver.lv/images/msn-icon.gif') no-repeat 5px center; } 
+3
source share

While @paislee's solution works, it is not ideal. When using the universal selector ( * ), each element is checked against it (since CSS maps from right to left). A better solution, especially if known to all child elements, should be to match individual elements. Ergo, button > img, button > span better than button > * .

 button { padding: 1px 6px 1px 6px; } /* Add this to align vertically */ button > img, button > span { vertical-align: middle; } 
 <button> <img src="https://placehold.it/50x50" alt="Text" /> <span>Text</span> </button> 
+15
source share

Fill + img height = line height. Maybe a little play with the gasket. It would be easier if img were an odd number height, since the center was one pixel and eitherside was an even number of pixels.

 button{ padding: 1px 6px 1px 6px; line-height: 24px; } button img{ width: 22px; height: 22px; vertical-align: middle; }​ 
+5
source share

Since we host content with a fixed height, we can use absolute positioning.

 button{ padding: 7px 7px 7px 30px; postion:relative; } button img{ width: 22px; height: 22px; position:absolute; left:5px; top:50%; margin-top:-11px; }​ 

Adjust padding and left positioning to your desired look.

+3
source share

The following style vertically aligns each direct child of a button:

 button > * { vertical-align: middle; } 
+3
source share

All Articles