Reputation: 23801
How to make an image be inside a div of certain height and width, without giving the img element any height or width.Here is the html code
<div class="frame" style="margin: 0 0.3em; width: 300px; height: 300px;">
<img id="photo" src="images/minnie-mouse-cartoon-wallpaper-600x600.jpg">
</div>
Here is the jsfiddle
Upvotes: 0
Views: 889
Reputation: 3786
Child elements will always reference their parent when you declare height and width in percentage. The image element in your example is a child to the div:
<div class="frame">
<img id="photo" src="http://hulza.files.wordpress.com/2012/07/brave_still_3.jpg" />
</div>
I moved the styles to a separate CSS sheet, JSFiddle was giving me issues with the inline styling:
.frame{
margin: 0 0.3em;
height:300px;
width:300px;
}
#photo{
max-height: 100%;
max-width: 100%;
}
I used max height and width because if the aspect ratio of the parent is incorrect the image won't render. With the max prefix, the image will resize itself to fit within the space given and maintain its aspect ratio. Both cases are in the JSFiddle.
http://jsfiddle.net/LDJGj/1/
http://jsfiddle.net/LDJGj/2/
Upvotes: 0
Reputation: 3278
You need to set your img
height
and width
as 100%
and set your required height
and width
in your div
This way it will same size of its parent.
Check out his FIDDLE
Upvotes: 0
Reputation: 20418
Try this
CSS
div{
width: 500px;
height: 300px;
display:inline-block;
vertical-align: top;
}
div img{
width: 100%;
height: 100%;
}
HTML
<div>
<img src="http://blog.gettyimages.com/wp-content/uploads/2013/01/Siberian-Tiger-Running-Through-Snow-Tom-Brakefield-Getty-Images-200353826-001.jpg" />
</div>
Upvotes: 0