Manolo
Manolo

Reputation: 26370

How to overlap a CSS background over an <img> tag?

I have an <img> tag inside an <a> tag:

<a href="urlPage" class="contain-video">
  <img src="urlImage" />
</a>

The <a> tag has the "contain-video" class, so I want to overlap a background image over the actual image:

//css file
.contain-video img {
    background: url('images/contain-video.png') no-repeat !important;
    z-index: 1;
}

but the background image is not shown. Any idea of how to achieve it?

Upvotes: 2

Views: 1988

Answers (2)

CodeToad
CodeToad

Reputation: 4724

To overlap an element on top of a child element, using css only, you can use the pseudo-elements :before or :after

http://jsfiddle.net/LpkwH/2/

.image-link {
    position: relative;
    display: inline-block;
    padding: 0;   
    margin: 10px;
}

.contain-video:after {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background-repeat: no-repeat;
    background-position: center;
    background-image: url(http://www.labiennale.org/img/play_icon.png);
}

HTML:

<a href="urlPage" class="image-link">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxrvTJX_MbF6LInvYHSMteauE-NBolAQjBT82zVuLFqECGmut67A" />
<a href="urlPage" class="image-link contain-video">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxrvTJX_MbF6LInvYHSMteauE-NBolAQjBT82zVuLFqECGmut67A" />

Upvotes: 5

JAB
JAB

Reputation: 21089

You could supply an overlay div with image background inside the anchor tag, with position: relative for the tag and position: absolute for the inner div and making the inner div fit its parent (as long as the a is set to display: block, as that's normally an inline element and thus it does not expand to contain the img, which is providing the size for the overlay).

See this fiddle for an example (hovering over the overlay div shows what's below): http://jsfiddle.net/wz7mx/3/

Note that there is no need to explicitly set z-index.

Upvotes: 1

Related Questions