I am trying to get an over sized image to scale to the size of a nested div. I have look at almost all of the Stack Questions that recommend setting max-width or max-height, but that does not work for my situation. Please see my code:
#parent2 { height: 100%; width: 100%; } #parent { height: 25%; width: 50%; } #parent img { max-height: 100%; }
<div id="parent2"> <div id="parent"> <img src="http://lorempixel.com/1000/1000"> </div> </div>
You should use max-width
and not max-height
.
Here is a working example:
#parent2 { height: 100%; width: 100%; } #parent { height: 25%; width: 50%; } #parent img { max-width: 100%; }
<div id="parent2"> <div id="parent"> <img src="http://lorempixel.com/1000/1000"> </div> </div>
Here is a fork to your jsfiddle:
https://jsfiddle.net/358vt90e/
try background-size: cover;
instead of max-height: 100%;
You can also use:
#parent img {
width: inherit;
}
I added a bunch of different cases for you. Bear in mind object-fit has pretty bad browser support. You'll need polyfills if you want to use it.
#parent2 { height: 100vh; width: 100%; } #parent { height: 25%; width: 50%; } #parent img { /* uncomment code below if you want image to respond to parent height */ /* width: auto; height: 100%; */ /* uncomment code below if you want image to respond to parent width */ /* width: 100%; height: auto; */ /* uncomment code below if you want image to respond to parent height and width */ width: 100%; height: 100%; object-fit: cover; object-position: center; }
<div id="parent2"> <div id="parent"> <img src="http://lorempixel.com/1000/1000"> </div> </div>
use
max-width:100%;
#parent2 { height: 100%; width: 100%; } #parent img { max-width:100%; }
<div id="parent2"> <div id="parent"> <img src="http://lorempixel.com/1000/1000"> </div> </div>
Use:
#parent img {
width: inherit;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.