Search code examples
htmlcssz-indexbackground-imageimage

Can a image tag in html z-index behind a css background image?


I have a css background image that I want in front of my img tag. The css background image has a z-index of 1, and the img tag has a z-index of 0. Am I allowed to put an img tag behind the css background with the z-index or will a css background always be behind an img tag regardless of it's z-index?


Solution

  • Sure, a HTML element with a background-image and a higher z-index can overlay any other HTML element, in your case a simple <img /> tag. But the <img> tag has not to be nested within the tag holding the background image.

    This will work

    <img src="../image.jpg" />
    <div style="background: url(../image2.gif); z-index: 1">Content</div>
    

    this not:

    <div style="background: url(../image2.gif); z-index: 1">
        <img src="../imag.jpg" />
    </div>