Jonah Bishop
Jonah Bishop

Reputation: 12581

How can I "contain" a background image?

I'm using a background image via CSS to style a few elements on my site. The problem I'm seeing in both Chrome and IE is that when the line-height of the line is smaller than the image is tall, the image gets cropped. Here's a fiddle that demonstrates the issue (again, view this with Chrome or IE to see the problem; Firefox renders things as I'd like), and here's the corresponding code from said fiddle:

HTML

<ul>
    <li class="icon"><a href="#">Link 1</a></li>
    <li class="icon"><a href="#">Link 2</a></li>
    <li class="icon">No Link Here</li>
</ul>

CSS

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}

ul li {
    display: inline;
    font-size: 13px;
    margin: 0 1em 0 0;
    padding: 0;
}

ul li.icon {
    background: url(http://www.borngeek.com/images/2013/stack_overflow_ex_01.gif) no-repeat left center;
    padding-left: 22px;
}

Note that in reality I don't hard-code the font-size in pixels; they just end up being rendered at 13 pixels high. I've hard-coded the value here to reproduce the problem.

None of the following seem to work:

Potential, problematic workarounds include:

Is there a cleaner way of handling this, or is one of the above workarounds my best bet? My only goal is for the parent element to be tall enough to render the entire 16x16 image.

Upvotes: 0

Views: 132

Answers (1)

Michael
Michael

Reputation: 7092

Force the LI's to have 2px of padding on the top and bottom (or just 3px to the top). The point of this is to make the height of the <li> equal or be greater than the height of the image, which is 16px. Your font size is 13px, so 3px padding to the top = 16px, or 2px to top and bottom = 17px which also works. This is the best way as it is sort of "best-practice".

http://jsfiddle.net/xkFfs/3/

padding: 2px 0;

OR, adjust the background-position:

http://jsfiddle.net/xkFfs/6/

background-position: 2px 0px;

Upvotes: 3

Related Questions