I have a div that contains an image. I want the image to resize with the div, but I do not want the image to ever have a height greater than 480px. I will post what I have below. It resizes with the div correctly, but it does not obey the max-height. If I move the mx height to the img css it does, but it will not resize then. I'm sure its something simple, but I can't seem to get it.
.feature_image {
max-height:480px
}
.feature_image img{
height: 100%;
width: 100%;
}
And here is the HTML
<div class="feature_image">
<img src="img/main-featured-image.png"/>
</div>
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.
It is mostly used with textarea and div elements. To disable resizable property of an element use resize to none.
The . A simple utility class, . full-width , will break the image out of it's parent container using some negative margins, relative positioning, and the viewport width ( vw ) unit of measure. Add it to your image, and the CSS handles the rest.
Making a child <div> element wider than the parent <div> can be done with some CSS properties. In the example below, we set the position of the parent <div> to “static”, which means that elements are placed according to the document’s normal flow. Here, we add the width of the parent container and specify its background-color and margin as well.
When you compare the two aspect ratios, 5:2 and 5:3.35, you see that the image is taller than the div.wrap element. .wrap { width: 500px; height: 200px; background: red; } .wrap * { width: 100%; height: 100%; }
The max-height property sets the maximum height of an element, and the max-width property sets the maximum width of an element. To resize an image proportionally, set either the height or width to "100%", but not both. If you set both to "100%", the image will be stretched.
Watch a video course CSS - The Complete Guide (incl. Flexbox, Grid & Sass) Create a <div> element with a class "box". Set the URL of your image in the <img> tag with the src attribute and specify the alt attribute as well. Set the height and width of the <div>.
Have you tried putting a display:block
?
Full CSS would look like:
.feature_image img {height: 100%; width: 100%; display:block;}
The reason behind your issue is that you did not specify the width
of the container but, in the same time, you set a width: 100%;
for the image.
I tested this with and it works just fine:
.feature_image {
height: 480px;
width: 480px;
}
.feature_image img{
height: 100%;
width: 100%;
}
This solution is good for small images, however it causes large images to distort, but there are solutions to overcome it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With