1

So I have some generated html that I am attempting to style. The html seems fairly normal to me, and the css I am trying to apply is minimal, but it is acting in a way that I would not expect.

The html places a div with an anchor tag, containing both an img and some text inside the div, wrapped (for some reason) in a span.

div {
    border: 1px solid black;
    height: 40px;
}


.title img {
    height: 100%    
}
<div>
    <span class="title ">
        <a href="http://www.google.com">
            <img src="https://upload.wikimedia.org/wikipedia/commons/9/91/Commons_app_72_72px.png">   
            <span>Sample Text</span>
        </a>
    </span>
</div>    

As you can see, the link text is outside the border of the div.

If I get rid of the image, the text is aligned properly, but adding the img seems to stretch the containing span outside the borders of the div its supposedly contained in, despite the fact that the img is not any bigger than the div and does not stretch to the new size of the span. It almost looks like the img and span inside the anchor are not aligned and the span is stretching to allow them to be weirdly offset.

The weird nesting of the div and span with class title is not something I have control over, so if the solution to my problem requires changing that, please explain why.

How do I get rid of this weird behavior?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Jason Bray
  • 502
  • 1
  • 4
  • 15

2 Answers2

1

Just add vertical-align: middle for image:

.title img {
    height: 100%;
    vertical-align: middle;
}

If you want to align text by top boundary than set vertical-align to top.

Images are inline element. By default strings are aligned to the baseline. Since image larger than text line height, text is aligned to the lower boundary.

Max Koshel
  • 177
  • 1
  • 11
1

An image, which is an inline element by default, is provided space underneath for descenders.

One way to resolve the issue is with vertical-align.

So instead of:

.title img {
    height: 100%;    
}

Try:

.title img {
    height: 100%;
    vertical-align: bottom;   
}

DEMO

Learn more about descenders here:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701