Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with CSS background image (Image not Showing)

Tags:

html

css

I am having a problem with a background image not showing.

I have a class that I've added to an anchor tag.

<a class="my-class"></a>

and the css for the class is:

.my-class {
    background:transparent url("../images/my-bg-image.png") no-repeat 0 center
 }

The problem is that the background image is not showing.

I know it's there because when I do this:

<a class="my-class">&NBSP;</a>

part of the image shows.

Anyone have any idea on how to make the whole image show without having to insert lots of &nbsp; 's please?

like image 713
Satch3000 Avatar asked Apr 14 '11 10:04

Satch3000


2 Answers

<a> tag is an inline element and without a content will not show the background, so You need to make it display as a block or inline-block element and then define the size of the element.

Try with:

.my-class {
    display:     block;
    width:       128px;
    height:      128px;
    background:  transparent url("../images/my-bg-image.png") no-repeat 0 center
}

For more information you can check the box model and the display property on the CSS 2.1 w3c standard.

Also the sections The width property and Computing widths and margins have an explanation of why the element doesn't show the background on an empty inline element.

Update:

Also the working draft of the CSS Box Model is available on the W3C site.

Update 2:

On a side note, relying only on a css background image for a link can have somme accessibility issues.

like image 115
pconcepcion Avatar answered Sep 23 '22 14:09

pconcepcion


The element has a zero-width because it has no content at all. If the image contains useful information (and it really should, it is used as a link!), you should put some text inside the link and use any image replacement technique you like, for example:

HTML:

<a class="my-class">It‘s awesome!</a>

CSS:

.my-class {
    background:transparent url("../images/my-bg-image.png") no-repeat 0 center;
    display: inline-block; /* create a block element behaving like an inline element */
    text-indent: -1000em; /* move the inner text outside of the link */
    overflow: hidden; /* prevent text visibility */
    width: 200px; /* image width */
    height: 16px; /* image height */
}
like image 40
mrcgrtz Avatar answered Sep 21 '22 14:09

mrcgrtz