Kartik Anand
Kartik Anand

Reputation: 4609

Vertical align text alongside SVG icon

I'm trying to align SVG icons alongside text. I've read lot of sources on how to do it, using vertical-align: middle being the best option for it.

I've also been able to do it, but there is one problem that I want answers to.

All the resources that I've seen, tell you to put vertical-align: middle only on the img element. E.g.

http://codepen.io/johnasp/pen/bqadn/
Vertically align text next to an image?

But in my particular case, I need to put vertical-align: middle on both the svg and the span element. The difference is very subtle. But it is there.

Here's the fiddle:

html, body {
    font-size: 32px;
}

.icon {
    height: 64px;
    width: 64px;
    vertical-align: middle;
}

span {
    vertical-align: middle; // Try commenting this line
}
<ul>
  <li>
    <svg viewBox='0 0 16 16' class="icon" >
      <path d="M7.5 1c-4.142 0-7.5 3.358-7.5 7.5s3.358 7.5 7.5 7.5c4.142 0 7.5-3.358 7.5-7.5s-3.358-7.5-7.5-7.5zM7.5 14.5c-3.314 0-6-2.686-6-6s2.686-6 6-6c3.314 0 6 2.686 6 6s-2.686 6-6 6zM8 8v-2h2v-1h-2v-1h-1v1h-2v4h2v2h-2v1h2v1h1v-1h2l-0-4h-2zM7 8h-1v-2h1v2zM9 11h-1v-2h1v2z">
      </path>
    </svg>
    <span>3.4Km</span>
  </li>
</ul>

Try commenting the line which is giving vertical alignment to span tag, and see that the text would shift upwards.

Can someone tell me why I need to vertical align both my svg and span tags and not just the svg as is working everywhere else?

Upvotes: 6

Views: 8309

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101918

The main reason you were having problems was because your icon isn't sitting centrally in your SVG viewBox.

Your viewBox is "0 0 16 16" but if you check it, the icon actually occupies "0 1 15 15". If you update the viewBox, it sits better on the line without having to vertically align your <span>.

html, body {
    font-size: 32px;
}

.icon {
    height: 64px;
    width: 64px;
    vertical-align: middle;
}

span {
}
<ul>
  <li>
    <svg viewBox='0 1 15 15' class="icon" id="foo">
      <path d="M7.5 1c-4.142 0-7.5 3.358-7.5 7.5s3.358 7.5 7.5 7.5c4.142 0 7.5-3.358 7.5-7.5s-3.358-7.5-7.5-7.5zM7.5 14.5c-3.314 0-6-2.686-6-6s2.686-6 6-6c3.314 0 6 2.686 6 6s-2.686 6-6 6zM8 8v-2h2v-1h-2v-1h-1v1h-2v4h2v2h-2v1h2v1h1v-1h2l-0-4h-2zM7 8h-1v-2h1v2zM9 11h-1v-2h1v2z">
      </path>
    </svg>
    <span>3.4Km</span>
  </li>
</ul>

Upvotes: 10

Related Questions