Reputation: 155
I'm trying to make this image responsive that it will resize and keep it aspect ratio at all sizes. However above 650px, its height won't increase but will just crop the top and bottom to keep the ratio and not stretch. Also I want the image height won't go below 200px and just the left and right. I want image to always be center too. Here is what I have so far: https://jsfiddle.net/4q83mh41/
<div class="hero">
<img src="http://wpdevserver.x10host.com/wp-content/themes/wp/img/hero1.jpg">
</div>
.hero {
width: 100%;
min-height:200px;
max-height: 650px;
position: relative;
}
.hero img {
width: 100%;
height:auto;
min-height:200px;
overflow: hidden;
max-height: 650px;
position:aboslute;
}
Many thanks
Upvotes: 0
Views: 2402
Reputation: 829
i figured out a css-only solution using a combination of the aspect ratio you want to use, the max-height that you want to use, and a min-width of 100% on the container element.
body {
margin: 0;
padding: 0;
}
.container {
aspect-ratio: 16/9;
min-width: 100%;
max-height: 350px;
}
.bg {
width: 100%;
height: 100%;
background-color: lightpink;
}
<div class="container">
<div class="bg"></div>
</div>
Upvotes: 0
Reputation: 1213
By adding some javascript, the position of the image can be adjusted dynamically inside the .hero
div. Additionally, CSS media queries can be used to keep the width of the image correct.
.hero {
width: 100%;
overflow: hidden;
max-height: 650px;
}
.hero img {
position: relative;
height: 200px;
width: auto;
}
@media (min-width:420px) {
.hero img {
width: 100%;
height: auto;
}
}
The javascript simply listens for resize events and adjusts the top
and right
properties of the relatively positioned image to keep it centered. Note that I'm using JQuery to manipulate the properties.
var heroresize = function() {
var aspect = 1800./858,
maxheight = 650,
minheight = 200,
width = $(".hero").width();
if(width < minheight*aspect) {
$(".hero img").css("right",(minheight*aspect - width)/2 + "px");
} else {
$(".hero img").css("right","0px");
}
if(width > maxheight*aspect) {
$(".hero img").css("top",(maxheight - width/aspect)/2 + "px");
} else {
$(".hero img").css("top","0px");
}
}
$(function(){
heroresize();
// remove if you don't need dynamic resizing
$(".hero").on("resize",heroresize);
});
The Javascript may cause some lag/stutter because resize events can be performance-intensive. If you don't need to worry about dynamic resizes, you can remove the indicated line.
I created a codepen you can play with here: http://codepen.io/regdoug/pen/azxVwd Note that the codepen has a max height of 350px because that allows you to see the effect without so much resizing.
Upvotes: 2