开发者

replacement for img tag

How can I replace this tag:

<img src="images/username_t.png" />

to use CSS?

H开发者_运维技巧ow can I show an image using CSS styles?


Html:

<div id="pic"></div>

CSS:

#pic {
    background-image: url('images/username_t.png');
    width: 100px; /* image width */
    height: 100px; /* image height */
    display: inline-block; /* so that it behaves like the img element */
}

For css, there are a few options dealing with background images, so check these out as well:

background-attachment
background-image
background-position
background-repeat
background-clip
background-origin
background-size


You can use something like the following; however, you really should only use this if it's for a background as it affects accessibility. Images shouldn't be controlled via CSS as the source of the image is not really a "styling-type" property. The source of the image belongs in the markup unless it is a background which obviously is a "styling-type" thing since it styles the page.

CSS:

<style type="text/css">
    #my_div {
        background: url('images/username_t.png');
        height: ?????px;
        width: ????px;
    }
</style>

HTML:

<div id="my_div"></div>

Feel free to take a look at the background CSS property.


Please check out this example: jsFiddle.net

background-image is a great way to implement this. You are given abilities now that you never had with an IMG tag. For example, you can repeat, position, clip, and resize with amazing ease.

<div id="image"></div>

/*css*/
#image {
    background-image: url(images/username_t.png);
    width: 200px;
    height: 900px;
}

Now lets say you wanted the user to position the IMG. You can do something like this, using these properties and a little jQuery

var originX, originY;
$('#image').mousedown(function (event) {
    originX = event.pageX;
    originY = event.pageY;
});
$('#image').mousemove(function(event) {
    var top = Math.abs(originX - event.pageX);
    var left = Math.abs(originY - event.pageY);
    $('#image').css('background-position', top + 'px ' + left + 'px');    
});    


i think no item behaves like the <img> tag. if you really want to do so you can define css classes that have a certain backround image attachment. but then you always need to supply min-width and min-height in order to see the image.


I'm not sure if I understand the question correctly, but if you just want to display an image that you don't feel is part of the content, you can use any element with a background image.

For example,

HTML:

<div id="thing"></div>

CSS:

#thing {
    background: url('images/username_t.png');
    width: 100px;
    height: 100px;
}

Of course, if you feel like the image is part of the content, you should use an image. If you want something that behaves like an image as far as user interaction (draggable to desktop, etc.), again you probably want an image.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜