Resizing image to perfectly fit a div with variable dimensions - javascript

I need to scale an image inside a div properly, so that the image keeps its proportions and so that either the width is equal to 100% or the height is equal to 100%.
So basically that the image takes up as much space as possible in the div whilst maintaining aspect ratio. And lets keep in mind that the div can change width and height.
So I have the intuition for this, but I don't have the code ...
The idea would be to get the ratio (height/width) of the div with
JavaScript/jQuery. => ratio A Then get ratio (height/width) of the image. => ratio B
Note: If ratio > 1, then we have a portrait image or div.
And if ratio < 1, then we have a landscape image or div.
If ratio A < ratio B, then we want height of image to be set at 100%;
If ratio A > ratio B, then we want width of image to be set at 100%;
So if we have a responsive div, width or height = 100% will change dynamically.
Is this possible?

Here are 2(css) solutions :
http://codepen.io/cryptcslaughtr/pen/LNoMBY
.container {
width: 100px;
height: 200px;
border: 1px solid #333;
background: url("https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png") no-repeat left top / contain;
}
<div class="container"></div>
http://codepen.io/cryptcslaughtr/pen/qZGLvE
.container {
width: 250px;
height: 130px;
border: 1px solid #333;
}
.container img {
max-width: 100%;
max-height: 100%;
}
<div class="container">
<img src="https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png" alt="Put your image" />
</div>

You can simply set parent div to position relative, and overflow hidden. And then do this:
.bg-img {
bottom: -1000px;
left: -1000px;
margin: auto;
min-height: 100%;
min-width: 100%;
position: absolute;
right: -1000px;
top: -1000px;
}
This will insure no matter whats the size of the container it will always cover it 100%. This will also contain image proportions.

If you need img tag for SEO/alt/ARIA/whatever, here is modified Cryptc_Slaughtr's solutions combined into one:
.container {
width: 250px;
height: 200px;
border: 1px solid #333;
background: url("https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png") no-repeat left top / contain;
}
.container img {
width:100%;
height: 100%;
opacity:0;
}
<div class="container"><img src="https://3.bp.blogspot.com/-W__wiaHUjwI/Vt3Grd8df0I/AAAAAAAAA78/7xqUNj8ujtY/s1600/image02.png" alt="Put your image" title="Put your image" /></div>

Related

To crop/resize an image to change the aspect ratio using CSS

I have an image of size 700px(width) x 333px(height) which have aspect ratio 2.10. I want to display this image in size 327px(width)and 183px(height) with aspect ratio 16:9.The original images could be cropped or resized with minimum distortion and final aspect ratio of each element should be 16:9 and displayed as 327px(width)and 183px(height).Following is the code I tried.
object-fit: cover; works fine, it crops and resizes the image to size 327px X 183px but it is not supported on all/older browsers versions. What could be an alternative to achieve the same result through CSS supported on all and older browsers?
/*original image : http://starmoz.com/images/lancia-gamma5.jpg */
.cropAndResize {
width: 327px;
height: 183px;
object-fit: cover;
}
<body>
<div>
<img src="http://starmoz.com/images/lancia-gamma5.jpg" class="cropAndResize">
</div>
</body>
For crop purpose I often make use of background-image on a element of type block or inline-block instead of relies on img tag:
.cropAndResize {
width: 327px;
height: 183px;
background-size: cover;
background-position: 50% 50%;
background-image: url('http://starmoz.com/images/lancia-gamma5.jpg');
}
<body>
<div class="cropAndResize"></div>
</body>
One simple solution could be:
.cropAndResize {
height: 183px;
margin-left: -20px;
}
div {
width: 327px;
overflow: hidden;
}
Maybe something like this could work for you? The only caveat is you need to set a specific margin to align the image within the container to center it.
.crop {
width: 327px;
height: 183px;
overflow: hidden;
position: relative;
border: 1px solid black;
}
.cropAndResize {
position: absolute;
min-width: 100%;
max-height: 100%;
margin: 0px 0px 0 -20px;
}
<body>
<div class="crop">
<img src="http://starmoz.com/images/lancia-gamma5.jpg" class="cropAndResize">
</div>
</body>

Make an image with a percentage width a perfect square using css

Hello I have an image in a container that is set to width: 100%.
I was wondering if there's any way to can have a height generated to make it a perfect square.
So say the original image is 450px wide and 300px tall.
The css gives it a width of 100% so it stretches and fills the container, but the image remains rectangular.
Is it possible to do some css or jquery trick to generate a height to make this image a perfect suqare?
I don't care if the image gets cropped or stretched out and looks funky, I just need it to be a perfect square.
Thanks!
So you are free to stretching out the image - this can be a CSS solution:
Make a square container based on the width by using padding-top: 100%
Position the image absolutely by stretching it out to the square container as desired.
See demo below:
.wrapper {
border: 1px solid red;
height: 0;
overflow: hidden;
padding-top: 100%;
box-sizing: border-box;
position: relative;
}
.wrapper img {
width: 100%;
vertical-align: top;
position: absolute;
top: 0;
left: 0;
height: 100%;
}
<div class="wrapper">
<img src="http://placehold.it/400x300" />
</div>
Using straight CSS you can set width and height to 100vw.
You could do so with the following jQuery
var img_width = $('#image').width();
$('#image').css({'height':img_width+'px'});
Hope that helps.
Since you don't care if the image is cropped or distorted, the layout is simple.
Just add overflow: hidden to the container. The image can be any size.
div {
height: 100px;
width: 100px;
border: 2px solid red;
overflow: hidden;
}
<div>
<img src="http://www.placekitten.com/450/300">
</div>

If image height exceeds image width, vertically center image by cropping its top and bottom - possible with only CSS?

Given a scenario where you don't know the height and width of image elements in advance, let's say that in cases where image height is greater than image width, you'd like to vertically center the image by cropping the same amount of pixels form its top and bottom, such that the new image height matches the image width. For example, if an image has a width of 200px, and its height is 250px, crop 25px from its top and from its bottom.
Here's an example setup:
HTML:
<div class = 'cell'>
...
<div class = 'image_container'>
...
<img ...>
</div>
</div>
CSS:
.cell {
display: inline-block;
float: left;
/* width will be changed by use of '#media screen'.
Smaller browser window -> larger width */
width: 31%;
}
.image_container {
position: relative;
float: left;
width: 100%;
}
.image_container > img {
width: 100%;
}
Is it possible to accomplish the aforementioned center/crop operation using only CSS, or is it necessary to use javascript/jquery for this?
You can use the object-fit CSS attribute. It acts a lot like the background-size attribute.
.image_container > img {
object-fit: contain;
}
Note that this doesn't have full browser support as of now (October 2016) so you may want to look into setting the image as a background on a div and using background-position and background-size to deal with this instead of an <img> tag.
.image_container {
height: 300px;
background-color: cornflowerblue;
image-rendering: pixelated;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAALklEQVQoU2NkgID/UBqdYmSESoJobOA/sgKQKTCFMDaKAuqYAHMs3CqiHInXmwDZGBMDEmk6SQAAAABJRU5ErkJggg==');
background-repeat: no-repeat;
background-position: center center;
background-size: 200px;
}
<div class="image_container"></div>
.cover_image {
height: 400px;
background: url('http://lorempixel.com/g/400/200/') no-repeat scroll center center;
background-size: cover;
}
<div class="cover_image"></div>

getting the height of a div to match the width when it shrinks responsively

In the jsfiddle here http://jsfiddle.net/H3VW5/ I have 3 divs where the width is based on perencentage. Is there a simple way (without having an image in it) to get the height to match a certain aspect ratio so that when the window shrinks the height shrinks with the width to keep the same shape? IE. if the div size was 600px x 600px at 60% and the window shrunk to make the width 500px the height would also shrink to 500px?
/*CSS:*/
.div1 {width:60%; height:400px; background-color:#066; float:left}
.div2 {width:20%; height:400px; background-color:#09F; float:left;}
.div3 {width:20%; height:400px; background-color:#C00; float:left;}
<!--HTML:-->
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
There is a good trick described here which may solve it for you.
Basically, you let the width just be auto (don't specify a px height), and use padding-bottom with a percentage (%). Neat.
How about setting a height and width on your body and html, and then changing the height of your div to percentages? This allows you to then set relative liquid heights on your div because now they have something to size to.
body, html { height: 100%; width: 100%; }
.div1 {width:60%; height:40%; background-color:#066; float:left}
.div2 {width:20%; height:40%; background-color:#09F; float:left;}
.div3 {width:20%; height:40%; background-color:#C00; float:left;}
JSfiddle link
You can use jquery to control the height of the divs
$(".ratio" ).each(function () {
var height = $(this).width();
console.log(height);
$(this).css('height',height + 'px');
});
Link : http://jsfiddle.net/gwx6y/
Here is what I came with. The only thing which is not hacky and it gets nice aspect ratiou keeping is an image. So, if change the markup a bit to:
<div class="wrapper">
<img src="bigimage.jpg" />
<div class="div1">a</div>
<div class="div2">b</div>
<div class="div3">c</div>
</div>
and set max-width: 100%; to the image its height will be changed like that so it keeps the original aspect ratio. So, we can use that and position the divs absolutelly, set the proper width and height to 100%. The dimensions of the image are leading here. The wrapper takes the same size and because the divs are childs of the same wrapper their height is also the same.
CSS:
.wrapper {
width: 100%;
position: relative;
}
.wrapper img {
position: relative;
max-width: 100%;
z-index: 1;
display: block;
opacity: 0;
}
.div1 {
position: absolute;
left: 0;
top: 0;
height: 100%;
width:60%;
background-color:#066;
z-index: 2;
}
.div2 {
position: absolute;
height: 100%;
left: 0;
top: 0;
left: 60%;
width:20%;
background-color:#09F;
z-index: 3;
}
.div3 {
position: absolute;
height: 100%;
left: 0;
top: 0;
left: 80%;
width:20%;
background-color:#C00;
z-index: 4;
}
Example of my solution is available here:
http://jsfiddle.net/krasimir/H3VW5/3/
P.S. The good thing in this approach is that you can keep whatever ratio you want. All you have to do is to create an image with that ratio.

Scale and center image in variable-size div using JS

http://jsfiddle.net/3qMnM/1/
HTML:
<div class="info-panel"></div>
<div class="image">
<img src="http://placehold.it/960x1400">
</div>
CSS:
.image {
height: 100%;
width: auto;
margin-right: 200px;
}
.info-panel {
position: fixed;
width: 200px;
height: 100%;
background-color: red;
right: 0px;
}
I'm trying to scale images down (never up) dynamically to fit into the image-div (without cropping), which is variable in height (100%) and width (set to auto). The image also needs to be centered (vertically and horizontally) and have equal padding of a few pixels top and bottom.
There is an info panel next to the image container as you can see in the fiddle, but I'm not sure if this is relevant.
Do my statements make sense?
Thanks, I have spent way too much time experimenting with this already! :/
If I understand correctly, you want something like this.
It scales down if the image is too large, but keeps the original size when it fits inside the window. In other words, it never scales up - only down.
It is a combination of CSS and some jQuery:
This short JS centers the image vertically:
function verticallyCenterImage(){
var $img = $('.image img'),
windowHeight = $(window).outerHeight();
if($img.height() < windowHeight){
var delta = windowHeight - $img.height();
$img.css('margin-top', (delta / 2) + 'px');
}else{
$img.attr('style', '');
}
}
And this line of CSS keeps the image centered horizontally:
.image {
padding-right: 200px;
text-align: center; /* <- this one */
max-height: 100%;
overflow: hidden;
}
And to keep the original size of the image, I just set the max height and width on the img inside the .image class, like so:
.image img {
max-width: 96%;
max-height: 96%;
margin: 2%;
}
You can adjust the size and margins to your needs, just remember to keep them in relation too each other :)
Some of the techniques discussed here could work for you:
http://css-tricks.com/centering-in-the-unknown/
The trick there is to use table elements, or CSS 2.1 table display.
Edit: More approaches here: http://www.vanseodesign.com/css/vertical-centering/
You are mixing px with %. If you want to achieve that only by CSS, you need to use % for both widths:
.image {
width: 85%;
}
.image img {
width: 100%;
}
.info-panel {
position: fixed;
width: 15%;
height: 100%;
background-color: red;
right: 0px;
}
... otherwise, you have to use JS to calculate the current available width on the left side and assing it the .image div:
HTML
<div class="info-panel"></div>
<div class="image">
<img src="http://placehold.it/960x1400" />
</div>
CSS
.image {
min-height: 600px;
width: auto;
}
.image img {
width: 100%;
}
.info-panel {
position: fixed;
width: 200px;
height: 100%;
background-color: red;
right: 0px;
}
JS (jQuery)
$(document).ready(function() {
$('.image')
.css('min-height', 'auto')
.height($(window).height())
.width($(window).width() - $('.info-panel').width())
;
});

Categories