CSS background image issue (image not showing)

I have a problem with a background image that is not showing.

I have a class that I added to the anchor tag.

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

and css for the class:

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

The problem is that the background image is not displayed.

I know this there, because when I do this:

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

part of the image is displayed.

Does anyone have an idea how to make an entire image without having to embed a lot of &nbsp; , you are welcome?

+7
source share
3 answers
Tag

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

Try:

 .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 and display property on CSS 2.1 w3c standard .

Also, the sections Property width and Calculation of width and margins explain why the element does not display the background on an empty inline element.

Update:

Also, the CSS Box Model working draft is available on the W3C website.

Update 2:

On the side, a note, relying only on a css background image for reference, may have accessibility issues.

+15
source

An element has zero width because it has no content at all. If the image contains useful information (and this is really necessary, it is used as a link!), You should put the text inside the link and use any image replacement technique that 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 */ } 
+5
source

You need to assign a binding width. String elements have no width if they have no content.

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

Edit: and, it seems, without any content, it is also necessary to set the height and display:inline-block . This makes the element think of itself internally as a block element, but act externally as an inline element.

+4
source

All Articles