Stan
Stan

Reputation: 26501

Align image and text in the middle of button element

What would be the best and easiest way to align text and image vertically in the middle of 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>

Upvotes: 15

Views: 55881

Answers (5)

0b10011
0b10011

Reputation: 18785

While @paislee's solution works, it is not ideal. With the universal selector (*) being used, every element is checked against it (as CSS is matched right-to-left). A better solution, especially if all children elements are known, is to match the elements individually. Ergo, button > img, button > span is 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>

Upvotes: 32

Andrew Bacon
Andrew Bacon

Reputation: 546

Since we're positioning fixed-height content, 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 desired look.

Upvotes: 3

calebds
calebds

Reputation: 26228

The following style vertically aligns every direct child of the button:

button > * {
    vertical-align: middle;
}

Upvotes: 4

Valamas
Valamas

Reputation: 24719

Padding + img height = line height. Could play with the padding a little. Would be easier if img was odd number height as center is one pixel and eitherside is even number of pixels.

button{
    padding: 1px 6px 1px 6px;
    line-height: 24px;
}

button img{
    width: 22px;
    height: 22px;
        vertical-align: middle;
}​

Upvotes: 6

TimCodes.NET
TimCodes.NET

Reputation: 4699

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;
}

Upvotes: 1

Related Questions