Select an image from CSS instead of HTML.

I have a difficult question. For some people this can be fun.

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

So the 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 or classes, just with this html markup!

Tried everything, but I think this is impossible?

+5
source share
2 answers

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

In this example, the red <img> is removed and replaced with a 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; } 
+2
source

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

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 img, you can use several methods, also using opacity, visibility: hidden, display: none; etc. Depends on what you are trying to achieve.

0
source

Source: https://habr.com/ru/post/1200492/


All Articles