htmlcss

CSS "vertical-align: middle" doesn't shrink the height of the parent element of img


I have an anchor element with img element inside. The img element has width and height of 16.

Why does the anchor element have a height of more than 16 even when I set vertical-align: middle on the img?

.brand-link {
  text-decoration: none;
}

.brand {
  vertical-align: middle;
}
<a href="#" class="brand-link">
    <img src="https://www.gravatar.com/avatar/89ef9ea23fc4a61a882a2a44f3ccf0b7?s=64&d=identicon&r=PG" alt="brand" width=16 height=16 class="brand">
</a>


Solution

  • The extra vertical space is due to the line height of the font, as img is a replaced element. The following styles may achieve what you want:

    .brand-link {
      display: block;
      width: fit-content;
      line-height: 0;
      text-decoration: none;
    }
    <a href="#" class="brand-link">
        <img src="https://www.gravatar.com/avatar/89ef9ea23fc4a61a882a2a44f3ccf0b7?s=64&d=identicon&r=PG" alt="brand" width=16 height=16 class="brand">
    </a>

    Another solution:

    .brand-link,
    .brand {
      display: block;
    }
    
    .brand-link {
      width: fit-content;
      text-decoration: none;
    }
    <a href="#" class="brand-link">
        <img src="https://www.gravatar.com/avatar/89ef9ea23fc4a61a882a2a44f3ccf0b7?s=64&d=identicon&r=PG" alt="brand" width=16 height=16 class="brand">
    </a>

    A good explanation for why this extra space appears: Image inside div has extra space below the image