YOU
YOU

Reputation: 1080

Pick Image from CSS instead of HTML

I have a tricky question. Might funny to some people here.

I am trying to overcome html img and use image via css background property.

So, Code is simple:

<a id="logo" href="/"><img src="/logo1.png"></a>

CSS

position: relative;
height: 85px;
width: 200px;
background: url(/logo2.png) no-repeat;
background-size: 200px 200px;

So, I want logo1 from html removed and css image logo2 overtake logo1.

NOTE: No extra divs and classes, Only with that html markup!

Tried everything but i think this is impossible?

Upvotes: 4

Views: 1210

Answers (2)

Alessandro Incarnati
Alessandro Incarnati

Reputation: 7246

If you want to hide the img tag and replace it with the background image. Use z-index and remove position:relative; from the link and apply it to the img instead. Add display:block; to the link and give it fixed dimensions.

HTML

<h2>Your actual code:</h2>
<a id="logo2" href="/"><img src="http://www.placehold.it/100x100" /></a>
<br> 
<h2>You want to hide the img tag and replace it with the background image. Use z-index and replace position:relative; and apply it to the img instead.</h2>
<a id="logo" href="/"><img src="http://www.placehold.it/100x100" /></a>

CSS

    #logo, #logo2{
        height: 100px;
        width: 200px;
        display:block;
        background: url(http://www.placehold.it/100x100) no-repeat;
        background-size: 200px 100px;
        z-index:2;
    }
    #logo img{
        z-index:-1;position:relative;
    }

DEMO http://jsfiddle.net/a_incarnati/stkrj9eq/

If you want to hide the img, you can use several techniques, also using opacity, visibility:hidden, display:none; etc. Depends what you are trying to achieve.

Upvotes: 0

misterManSam
misterManSam

Reputation: 24692

Remove the img with display: none and use display: block/inline-block/table-cell to get your height and width.

In this example the red <img> is being removed and replaced with the yellow CSS background image.

Example!

HTML

<a id="logo" href="/"><img src="http://www.placehold.it/200/FF0000"></a>

CSS

a { 
   position: relative;
   height: 85px;
   width: 200px;
   background: url(http://www.placehold.it/200/FFFF00) no-repeat;
   background-size: 200px 200px;
   display: block;
}
a img {
    display: none;
}

Upvotes: 2

Related Questions