css - Keeping aspect ratio of image but cropping when hitting max/min height -
i'm trying make image responsive resize , keep aspect ratio @ sizes. above 650px, height won't increase crop top , bottom keep ratio , not stretch. want image height won't go below 200px , left , right. want image center too. here have 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
by adding javascript, position of image can adjusted dynamically inside .hero div. additionally, css media queries can used keep width of 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 listens resize events , adjusts top , right properties of relatively positioned image keep centered. note i'm using jquery manipulate 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 don't need dynamic resizing $(".hero").on("resize",heroresize); }); the javascript may cause lag/stutter because resize events can performance-intensive. if don't need worry dynamic resizes, can remove indicated line.
i created codepen can play here: http://codepen.io/regdoug/pen/azxvwd note codepen has max height of 350px because allows see effect without resizing.
Comments
Post a Comment