Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an image in div with CSS?

Tags:

css

image

I would like to have all my images in CSS (the only way I know how is to put them in as background images).

But the problem in this solution is you can never let the div take the size of the image.

So my question is: what is the best way to have the equivalent of <div><img src="..." /></div> in CSS?

like image 452
Dany Y Avatar asked May 31 '12 08:05

Dany Y


People also ask

How do I display an image in a div?

When you need to center an image inside a <div> tag, you can apply the text-align:center CSS property to the <div> tag. Then, you need to add the class into the <div> tag that contains the <img> tag.

How do you put an image in a div in HTML?

To insert an image in HTML, use the image tag and include a source and alt attribute. Like any other HTML element, you'll add images to the body section of your HTML file. The HTML image element is an “empty element,” meaning it does not have a closing tag.

How do I embed an image in CSS?

To add images to a page, we use the <img> inline element. The <img> element is a self-containing, or empty, element, which means that it doesn't wrap any other content and it exists as a single tag. For the <img> element to work, a src attribute and value must be included to specify the source of the image.


2 Answers

This answer by Jaap :

<div class="image"></div>​ 

and in CSS :

div.image::before {    content:url(http://placehold.it/350x150); }​ 

you can try it on this link : http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

like image 76
Dany Y Avatar answered Oct 24 '22 17:10

Dany Y


you can do this:

<div class="picture1">&nbsp;</div> 

and put this into your css file:

div.picture1 {    width:100px; /*width of your image*/    height:100px; /*height of your image*/    background-image:url('yourimage.file');    margin:0; /* If you want no margin */    padding:0; /*if your want to padding */ } 

otherwise, just use them as plain

like image 31
JudeJitsu Avatar answered Oct 24 '22 18:10

JudeJitsu