Joe Joe - 24 days ago 6
CSS Question

img that fits into a div

I want a background image that automatically fits the div size.

I have several div of the same class, each with different dimensions, is it possible to set the width and the height of the image, exactly to the dimension of the div ?

Do you think is better to use

img
or
background-image
?

P.S I don't know if is it possible to set the dimension of the background image, of course is possible for the tag img, but if I use the tag img the image is separated from the content (it dosen't overlap as a background)

Answer

Personally if you're going to modify things in this way, I think using img is better.

You can literally just set the height and width of the div if that's what you want.

<div class="box"><img src="Path/to/image.png"/></div>

and then the CSS would be something like this:

.box {
     height: 300px;
     width: 300px;
}

.box img {
     height: 300px;
     width: 300px;
}

That's one way of doing it anyway. You could also set it so that the height is 100% the size of the div, but the width is set to auto so that it scales with it. That way the image won't distort. Like this:

.box img {
     height: 300px;
     width: auto;
}