use CSS? How can I show an image using CSS styles? +4 ...">

Replacing the img tag

How to replace this tag:

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

use CSS?

How can I show an image using CSS styles?

+4
source share
5 answers

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 */ } 

There are several background image options for css, so also check them out:

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

+10
source

Please check out this example: jsFiddle.net

background-image is a great way to implement this. You are now given abilities that you have 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 let's say you wanted the user to host the IMG. You can do something like this using these properties and a bit of 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'); }); 
+1
source

You can use something like the following; however, you really should only use this if it is used for the background, as it affects accessibility. Images should not be manipulated using CSS, since the source of the image is not a โ€œstyle propertyโ€. The source of the image belongs to the markup, unless it is a background, which is obviously a โ€œstyle typeโ€ as 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> 

Remember to take a look at the CSS CSS property .

+1
source

I think that no element behaves like an <img> tag. if you really want to do this, you can define css classes that have a specific background image attachment. but then you always need to feed the minimum width and minimum height to see the image.

0
source

I'm not sure if I understood 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 instance,

HTML:

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

CSS

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

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

0
source

All Articles