Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch Image to Fit 100% of Div Height and Width

Tags:

html

css

I have a div with the following CSS

#mydiv{
    top: 50px;
    left: 50px;
    width: 200px;
    height: 200px;
}

and my HTML looks like this

<div id = "mydiv">
    <img src = "folder/file.jpg" width = "200px" height = "200px">
</div>

I'd like my web image to always be the same size (in a 1:1 aspect ration) no matter what the resolution of the actual image is. If my actual image files are square (with 1:1 ratio) then this isn't a problem. But if the actual image files are not square then the displayed web image do stretch to 100% of both the div's height and width (in this case 200px).

How do I get different image sizes to fit to my DIV?

like image 201
Lloyd Banks Avatar asked May 11 '13 20:05

Lloyd Banks


People also ask

How do I make a picture fit a div perfectly?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

How do I stretch an image to fit in HTML?

If your image doesn't fit the layout, you can resize it in the HTML. One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.

How do I stretch a fit image in CSS?

You can use the CSS background-size: cover; to stretch and scale an image in the background with CSS only. This scales the image as large as possible in such a way that the background area is completely covered by the background image, while preserving its intrinsic aspect ratio.


3 Answers

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200"> 

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;"> 

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {     width: 200px;     height: 200px; } 

or

#mydiv img {     width: 100%;     height: 100%; } 
like image 144
bfavaretto Avatar answered Oct 18 '22 07:10

bfavaretto


Instead of setting absolute widths and heights, you can use percentages:

#mydiv img {     height: 100%;     width: 100%; } 
like image 35
dodgerogers747 Avatar answered Oct 18 '22 09:10

dodgerogers747


Or you can put in the CSS,

<style>
div#img {
  background-image: url(“file.png");
  color:yellow (this part doesn't matter;
  height:100%;
  width:100%;
}
</style>
like image 43
Haze811 Avatar answered Oct 18 '22 09:10

Haze811