简体   繁体   中英

Convert html img tag to css

How do I convert and img tag to css so I don't have to have a million img tags. Or whats the best way todo images with css

<img src="hg-rx.gif" name="foo" width="18" height="18">

I tried background:url in css and it needs text for it to display properly, id hilight and the image would disappear

.hg-text-rx {
  background:url(hg-rx.gif);
  background-repeat: no-repeat;
  position: relative;
 }

You can do this with just css by using a div or other block element of fixed width and height and make the image the background of that. But to do this, you must still put the div (for the image) in the HTML so you aren't really cleaning anything up, unless you are just trying to make the site easier to skin completely using CSS. However, this does make rollover states a breeze.

div#hg-rx {
display:block;
width:18px;
height:18px;
background: url(hg-rx.gif) 0 0 no-repeat transparent;
}

<div id="hg-rx"></div>

If you are doing borders, rounded corners or buttons you might want to look into sprites. http://css-tricks.com/css-sprites/

you can add a image as background in css, but you must set the width and height of image to be visible.

css

.hg-text-rx {background:url("http://dummyimage.com/200x200/000/545");width:200px;height:200px};

Demo: http://jsfiddle.net/2XX8A/

Actually, while this cannot be done strictly in CSS, if you have IMG tags and want to convert them to divs, you can do so using jQuery (a javascript wrapper) on the fly pretty easily.

LIVE DEMO http://jsfiddle.net/Epgvc/4/

HTML

<img src='http://dummyimage.com/200x200/000/fff&text=image1' />
<img src='http://dummyimage.com/100x100/f00/ff0&text=image2' />
<img src='http://dummyimage.com/250x50/0ff/fff&text=image3' />

JS

$('img').each(function(){
    var html="<div style='border:1px solid #ff0;width:" + $(this).width() + "px;height:" + $(this).height() + "px;background:url(" + $(this).attr('src')+ ");color:#fff;'>This is a Div!</div>"
    $(html).insertBefore($(this));
    $(this).remove(); //Comment out this line if you want to leave the original image
});

If you intent on having the image as a background to a text field you could alway use text-indent

.hg-text-rx {
  background:url(hg-rx.gif);
  background-repeat: no-repeat;
  position: relative;
**text-indent:-10000px;**
 }

<p> this text wont show, but the image will </p>

However there is conflicting arguments about this technique from a seo point of view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM