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
's please?
<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.
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 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With