How to make centre cropped image responsive? - html

Based on an existing answer, I have managed to centre crop an image. I am having trouble making the centre cropped image responsive, though.
Question
When I reduce the size of the web browser window, the centre cropped image does not scale down nicely. Instead, it maintains it's fixed height and width and spills out of the view-port. The problem is perhaps demonstrated more clearly with a Fiddle.
How can I make the centre cropped image scale down nicely? Ideally the centre cropped image will scale down nicely while still being cropped and maintaining a similar aspect ratio.
.centered-container {
max-width: 960px;
margin: auto;
}
.center-cropped-img {
width: 640px;
height: 360px;
overflow: hidden;
margin: 10px auto;
border: 1px red solid;
position: relative;
}
.center-cropped-img img {
position: absolute;
left: -100%;
right: -100%;
top: -100%;
bottom: -100%;
margin: auto;
min-height: 100%;
min-width: 100%;
}
<div class="centered-container">
<div class="center-cropped-img">
<img src="http://i.imgur.com/Ag2ZCgz.png" alt="" />
</div>
<div class="center-cropped-img">
<img src="http://i.imgur.com/BQUgmlB.png" alt="" />
</div>
</div>
Again, here is a Fiddle that perhaps demonstrates the problem better than in prose.

Read the comments in the code for an explanation.
JSFiddle
HTML
<div class="container">
<img src="http://i.imgur.com/Ag2ZCgz.png" alt="" />
</div>
<div class="container">
<img src="http://i.imgur.com/BQUgmlB.png" alt="" />
</div>
CSS
/*some basic markup for a flexible container to crop the image*/
.container {
width: 80%;
border: 3px red double;
margin: 50px auto;
padding:0;
overflow: hidden;/*do not show image that is overflowing*/
background-color: yellow;
}
.container img {
display: block;
width: 200%;/** (1 / part of the total image width you want shown)*100% In this example you want to show 50% of the image-width**/
margin-left:-50%;/*move the image to the left, removing that content from view (and making content on the right appear). -0% will show the left side of the image. The negative value of the defined width in the rule before this one + 100% will show you the right side of the image. I guess you can figure the rest out by changing this value.*/
margin-top: -25%;/*changing the top and bottom values is a bit of a pain. After some trial and error (in google chrome) it appears they are based on the width of the image container, not the height (how unusual is that!!!). So putting -100% in this value would (re)move the image up by the px value of the width of the #container div. If you are using css sprites you should avoid setting this value other than 0%.
Alternatively do some math on the original dimensions of the image: -(vertical pixels you want off the image)/(image width)* 100% should work for pixel precision).
The good news is that the image scales with the #container div. So the image grows and shrinks with the container showing the exact same part of the image (and not showing more/less content).*/
margin-bottom:-25%;/*(re)move some of the bottom part of the image. See margin-top for more (works identical)*/
}

Use the padding hack.
U need a container, which you set to be a width in percent, height of 0 and padding on the bottom to create the aspect ratio you are looking for.
If you can set your image as a background it's even easier.
I have written a sass mixin for that, and also a small tutorial on my blog which comes with a little more extensive explanation: http://bekreatief.blogspot.ch/2014/09/padding-hack-sass-faux-color-overlay.html
If you need to have your image in an image tag, let me know, it's possible as well, but not as fast

Does adding this (fiddle) to .center-cropped-img achieve what you want? or do you not want to change the area that is being cropped?
max-width: 640px;
width: 100%;

Does this Fiddle do the right cropping?
With the following CSS we can maintain the aspect ratio of the container when resizing the window.
width: 640px;
max-width: 100%;
height: 0;
padding-bottom: 50%; // 320px or lower (half of the width)

The following solution uses CSS background-size property. The image is placed in the background. The <img> tag is used so that search engines can see the image.
/* responsive 40% wide, 4:3 aspect ratio container */
.centered-image {
width: 40%;
padding-top: 30%;
background-position: center center;
/* optional */
margin: 1em auto;
box-shadow: 0 0 .5em .25em black;
}
.centered-image.cropped {
background-size: cover;
}
.centered-image.scaled {
background-size: contain;
background-repeat: no-repeat;
}
/* use your favorite text hiding technique */
.centered-image img {
display: none;
}
/* miscellaneous */
body {
margin: 0;
padding: 0;
}
h1 {
width: 40%;
margin: 1em auto;
font: bold medium monospace;
}
<h1>Cropped to Fit</h1>
<div class="centered-image cropped" style="background-image: url(http://lorempixel.com/400/400/sports/1/);">
<img src="http://lorempixel.com/400/400/sports/1/" width="400" height="400" alt="">
</div>
<div class="centered-image cropped" style="background-image: url(http://lorempixel.com/400/200/sports/2/);">
<img src="http://lorempixel.com/400/200/sports/2/" width="400" height="200" alt="">
</div>
<div class="centered-image cropped" style="background-image: url(http://lorempixel.com/200/400/sports/3/);">
<img src="http://lorempixel.com/200/400/sports/3/" width="200" height="400" alt="">
</div>
<h1>Scaled to Fit</h1>
<div class="centered-image scaled" style="background-image: url(http://lorempixel.com/400/400/sports/1/);">
<img src="http://lorempixel.com/400/400/sports/1/" width="400" height="400" alt="">
</div>
<div class="centered-image scaled" style="background-image: url(http://lorempixel.com/400/200/sports/2/);">
<img src="http://lorempixel.com/400/200/sports/2/" width="400" height="200" alt="">
</div>
<div class="centered-image scaled" style="background-image: url(http://lorempixel.com/200/400/sports/3/);">
<img src="http://lorempixel.com/200/400/sports/3/" width="200" height="400" alt="">
</div>

I have tried with a script. I simply created a function and called on loading and re-sizing.
jQuery
$(document).ready(function () {
heightMan();
$(window).resize(function () {
heightMan();
});
});
function heightMan() {
var winHeight = $(window).height();
var winHeight_50 = (winHeight / 2) - 20;
var container_node = $('.center-cropped-img');
var container_height = container_node.height();
container_height = winHeight_50;
container_node.css('height', container_height);
}
CSS Changes
.center-cropped-img {
width: 64%;
overflow: hidden;
margin: 10px auto;
border: 1px red solid;
position: relative;
}
See in action.

just give width in % instead of px .
.center-cropped-img {
width: 640px;// add in %
height: auto;
overflow: hidden;
margin: 10px auto;
border: 1px red solid;
position: relative;
}

Related

Adaprting an image to the div without changing aspect ratio [duplicate]

I want to show an image from an URL with a certain width and height even if it has a different size ratio.
So I want to resize (maintaining the ratio) and then cut the image to the size I want.
I can resize with html img property and I can cut with background-image.
How can I do both?
Example:
This image:
Has the size 800x600 pixels and I want to show like an image of 200x100 pixels
With img I can resize the image 200x150px:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
That gives me this:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
And with background-image I can cut the image 200x100 pixels.
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Gives me:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
How can I do both?
Resize the image and then cut it the size I want?
You could use a combination of both methods eg.
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 400px;
height: 300px;
margin: -75px 0 0 -100px;
}
<div class="crop">
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
</div>
You can use negative margin to move the image around within the <div/>.
With CSS3 it's possible to change the size of a background-image with background-size, fulfilling both goals at once.
There are a bunch of examples on css3.info.
Implemented based on your example, using donald_duck_4.jpg. In this case, background-size: cover; is just what you want - it fits the background-image to cover the entire area of the containing <div> and clips the excess (depending on the ratio).
.with-bg-size {
background-image: url('https://i.stack.imgur.com/wPh0S.jpg');
width: 200px;
height: 100px;
background-position: center;
/* Make the background image cover the area of the <div>, and clip the excess */
background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>
css3 background-image background-size
Did you try to use this?
.centered-and-cropped { object-fit: cover }
I needed to resize image, center (both vertically and horizontally) and than crop it.
I was happy to find, that it could be done in a single css-line.
Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110
Here is the CSS and HTMLcode from that example:
.centered-and-cropped { object-fit: cover }
<h1>original</h1>
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="200" height="200"
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
img {
position: absolute;
clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
Thanks sanchothefat.
I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
object-fit may help you, if you're playing with <img> tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
A small addition to the previous answers that includes object-fit: cover:
object-position
You can alter the alignment of the replaced element's content object within the element's box using the object-position property.
.trimmed-cover {
object-fit: cover;
width: 100%;
height: 177px;
object-position: center 40%;
}
<img class="trimmed-cover" src="http://i.stack.imgur.com/wPh0S.jpg">
img {
position: absolute;
clip: rect(0px,60px,200px,0px);
}
Try using the clip-path property:
The clip-path property lets you clip an element to a basic shape or to
an SVG source.
Note: The clip-path property will replace the deprecated clip
property.
img {
width: 150px;
clip-path: inset(30px 35px);
}
<img src="http://i.stack.imgur.com/wPh0S.jpg">
More examples here.
Live Example:
https://jsfiddle.net/de4Lt57z/
HTML:
<div class="crop">
<img src="example.jpg" alt="..." />
</div>
CSS:
.crop img{
width:400px;
height:300px;
position: absolute;
clip: rect(0px,200px, 150px, 0px);
}
Explanation:
Here image is resized by width and height value of the image. And crop is done by clip property.
For details about clip property follow:
http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/
In the crop class, place the image size that you want to appear:
.crop {
width: 282px;
height: 282px;
overflow: hidden;
}
.crop span.img {
background-position: center;
background-size: cover;
height: 282px;
display: block;
}
The html will look like:
<div class="crop">
<span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>
<p class="crop"><a href="http://templatica.com" title="Css Templates">
<img src="img.jpg" alt="css template" /></a></p>
.crop {
float: left;
margin: .5em 10px .5em 0;
overflow: hidden; /* this is important */
position: relative; /* this is important too */
border: 1px solid #ccc;
width: 150px;
height: 90px;
}
.crop img {
position: absolute;
top: -20px;
left: -55px;
}
There are services like Filestack that will do this for you.
They take your image url and allow you to resize it using url parameters. It is pretty easy.
Your image would look like this after resizing to 200x100 but keeping the aspect ratio
The whole url looks like this
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
but the important part is just
resize=width:200/crop=d:[0,25,200,100]
You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.
What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.
It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
If you are using Bootstrap, try using { background-size: cover;
} for the <div> maybe give the div a class say <div class="example" style=url('../your_image.jpeg');> so it becomes
div.example{
background-size: cover}
I needed to do this recently. I wanted to make a thumbnail-link to a NOAA graph. Since their graph could change at any time, I wanted my thumbnail to change with it. But there's a problem with their graph: it has a huge white border at the top, so if you just scale it to make the thumbnail you end up with extraneous whitespace in the document.
Here's how I solved it:
http://sealevel.info/example_css_scale_and_crop.html
First I needed to do a little bit of arithmetic. The original image from NOAA is 960 × 720 pixels, but the top seventy pixels are a superfluous white border area. I needed a 348 × 172 thumbnail, without the extra border area at the top. That means the desired part of the original image is 720 - 70 = 650 pixels high. I needed to scale that down to 172 pixels, i.e., 172 / 650 = 26.5%. That meant 26.5% of 70 = 19 rows of pixels needed to be deleted from the top of the scaled image.
So…
Set the height = 172 + 19 = 191 pixels:
height=191
Set the bottom margin to -19 pixels (shortening the image to 172 pixels high):
margin-bottom:-19px
Set the top position to -19 pixels (shifting the image up, so that the top 19 pixel rows overflow & are hidden instead of the bottom ones):
top:-19px
The resulting HTML looks like this:
<a href="…" style="display:inline-block;overflow:hidden">
<img width=348 height=191 alt=""
style="border:0;position:relative;margin-bottom:-19px;top:-19px"
src="…"></a>
As you can see, I chose to style the containing <a> tag, but you could style a <div>, instead.
One artifact of this approach is that if you show the borders, the top border will be missing. Since I use border=0 anyhow, that wasn't an issue for me.
You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.
Upload the image somewhere you prefer (S3, imgur etc.)
Plug it into your dedicated API url (from our dashboard)
You can also use a tool called Croppie that can crop images...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="https://foliotek.github.io/Croppie/croppie.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="https://foliotek.github.io/Croppie/croppie.js"> </script>
<script src="https://foliotek.github.io/Croppie/bower_components/exif-js/exif.js"> </script>
<style>
#page {
background: #ffffff;
padding: 20px;
margin: 20px;
}
#demo-basic {
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<h1>Crop Image Demo</h1>
<input id="upload" type="file" />
<br />
<div id="page">
<div id="demo-basic"></div>
</div>
<input id="upload-result" type="button" value="Crop Image"/>
<br />
<img id="cropped-result" src=""/>
<script>
var $uploadCrop;
$("#upload").on("change", function () { readFile(this); show(); });
$("#upload-result").on("click", function (ev) {
$uploadCrop.croppie("result", {
type: "canvas",
size: "viewport"
}).then(function (resp) {
$("#cropped-result").attr("src", resp);
});
});
function show() {
$uploadCrop = $("#demo-basic").croppie({
viewport: { width: 100, height: 100 },
boundary: { width: 300, height: 300 },
enableResize: true,
enableOrientation: true,
mouseWheelZoom: 'ctrl',
enableExif: true
});
}
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#demo-basic").addClass("ready");
$uploadCrop.croppie("bind", {
url: e.target.result
}).then(function () {
console.log("jQuery bind complete");
});
}
reader.readAsDataURL(input.files[0]);
}
else {
alert("Sorry - you're browser doesn't support the FileReader API");
}
}
</script>
</body>
</html>

How to crop image by table cell? [duplicate]

I want to show an image from an URL with a certain width and height even if it has a different size ratio.
So I want to resize (maintaining the ratio) and then cut the image to the size I want.
I can resize with html img property and I can cut with background-image.
How can I do both?
Example:
This image:
Has the size 800x600 pixels and I want to show like an image of 200x100 pixels
With img I can resize the image 200x150px:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
That gives me this:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
And with background-image I can cut the image 200x100 pixels.
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Gives me:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
How can I do both?
Resize the image and then cut it the size I want?
You could use a combination of both methods eg.
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 400px;
height: 300px;
margin: -75px 0 0 -100px;
}
<div class="crop">
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
</div>
You can use negative margin to move the image around within the <div/>.
With CSS3 it's possible to change the size of a background-image with background-size, fulfilling both goals at once.
There are a bunch of examples on css3.info.
Implemented based on your example, using donald_duck_4.jpg. In this case, background-size: cover; is just what you want - it fits the background-image to cover the entire area of the containing <div> and clips the excess (depending on the ratio).
.with-bg-size {
background-image: url('https://i.stack.imgur.com/wPh0S.jpg');
width: 200px;
height: 100px;
background-position: center;
/* Make the background image cover the area of the <div>, and clip the excess */
background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>
css3 background-image background-size
Did you try to use this?
.centered-and-cropped { object-fit: cover }
I needed to resize image, center (both vertically and horizontally) and than crop it.
I was happy to find, that it could be done in a single css-line.
Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110
Here is the CSS and HTMLcode from that example:
.centered-and-cropped { object-fit: cover }
<h1>original</h1>
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="200" height="200"
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
img {
position: absolute;
clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
Thanks sanchothefat.
I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
object-fit may help you, if you're playing with <img> tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
A small addition to the previous answers that includes object-fit: cover:
object-position
You can alter the alignment of the replaced element's content object within the element's box using the object-position property.
.trimmed-cover {
object-fit: cover;
width: 100%;
height: 177px;
object-position: center 40%;
}
<img class="trimmed-cover" src="http://i.stack.imgur.com/wPh0S.jpg">
img {
position: absolute;
clip: rect(0px,60px,200px,0px);
}
Try using the clip-path property:
The clip-path property lets you clip an element to a basic shape or to
an SVG source.
Note: The clip-path property will replace the deprecated clip
property.
img {
width: 150px;
clip-path: inset(30px 35px);
}
<img src="http://i.stack.imgur.com/wPh0S.jpg">
More examples here.
Live Example:
https://jsfiddle.net/de4Lt57z/
HTML:
<div class="crop">
<img src="example.jpg" alt="..." />
</div>
CSS:
.crop img{
width:400px;
height:300px;
position: absolute;
clip: rect(0px,200px, 150px, 0px);
}
Explanation:
Here image is resized by width and height value of the image. And crop is done by clip property.
For details about clip property follow:
http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/
In the crop class, place the image size that you want to appear:
.crop {
width: 282px;
height: 282px;
overflow: hidden;
}
.crop span.img {
background-position: center;
background-size: cover;
height: 282px;
display: block;
}
The html will look like:
<div class="crop">
<span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>
<p class="crop"><a href="http://templatica.com" title="Css Templates">
<img src="img.jpg" alt="css template" /></a></p>
.crop {
float: left;
margin: .5em 10px .5em 0;
overflow: hidden; /* this is important */
position: relative; /* this is important too */
border: 1px solid #ccc;
width: 150px;
height: 90px;
}
.crop img {
position: absolute;
top: -20px;
left: -55px;
}
There are services like Filestack that will do this for you.
They take your image url and allow you to resize it using url parameters. It is pretty easy.
Your image would look like this after resizing to 200x100 but keeping the aspect ratio
The whole url looks like this
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
but the important part is just
resize=width:200/crop=d:[0,25,200,100]
You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.
What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.
It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
If you are using Bootstrap, try using { background-size: cover;
} for the <div> maybe give the div a class say <div class="example" style=url('../your_image.jpeg');> so it becomes
div.example{
background-size: cover}
I needed to do this recently. I wanted to make a thumbnail-link to a NOAA graph. Since their graph could change at any time, I wanted my thumbnail to change with it. But there's a problem with their graph: it has a huge white border at the top, so if you just scale it to make the thumbnail you end up with extraneous whitespace in the document.
Here's how I solved it:
http://sealevel.info/example_css_scale_and_crop.html
First I needed to do a little bit of arithmetic. The original image from NOAA is 960 × 720 pixels, but the top seventy pixels are a superfluous white border area. I needed a 348 × 172 thumbnail, without the extra border area at the top. That means the desired part of the original image is 720 - 70 = 650 pixels high. I needed to scale that down to 172 pixels, i.e., 172 / 650 = 26.5%. That meant 26.5% of 70 = 19 rows of pixels needed to be deleted from the top of the scaled image.
So…
Set the height = 172 + 19 = 191 pixels:
height=191
Set the bottom margin to -19 pixels (shortening the image to 172 pixels high):
margin-bottom:-19px
Set the top position to -19 pixels (shifting the image up, so that the top 19 pixel rows overflow & are hidden instead of the bottom ones):
top:-19px
The resulting HTML looks like this:
<a href="…" style="display:inline-block;overflow:hidden">
<img width=348 height=191 alt=""
style="border:0;position:relative;margin-bottom:-19px;top:-19px"
src="…"></a>
As you can see, I chose to style the containing <a> tag, but you could style a <div>, instead.
One artifact of this approach is that if you show the borders, the top border will be missing. Since I use border=0 anyhow, that wasn't an issue for me.
You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.
Upload the image somewhere you prefer (S3, imgur etc.)
Plug it into your dedicated API url (from our dashboard)
You can also use a tool called Croppie that can crop images...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="https://foliotek.github.io/Croppie/croppie.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="https://foliotek.github.io/Croppie/croppie.js"> </script>
<script src="https://foliotek.github.io/Croppie/bower_components/exif-js/exif.js"> </script>
<style>
#page {
background: #ffffff;
padding: 20px;
margin: 20px;
}
#demo-basic {
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<h1>Crop Image Demo</h1>
<input id="upload" type="file" />
<br />
<div id="page">
<div id="demo-basic"></div>
</div>
<input id="upload-result" type="button" value="Crop Image"/>
<br />
<img id="cropped-result" src=""/>
<script>
var $uploadCrop;
$("#upload").on("change", function () { readFile(this); show(); });
$("#upload-result").on("click", function (ev) {
$uploadCrop.croppie("result", {
type: "canvas",
size: "viewport"
}).then(function (resp) {
$("#cropped-result").attr("src", resp);
});
});
function show() {
$uploadCrop = $("#demo-basic").croppie({
viewport: { width: 100, height: 100 },
boundary: { width: 300, height: 300 },
enableResize: true,
enableOrientation: true,
mouseWheelZoom: 'ctrl',
enableExif: true
});
}
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#demo-basic").addClass("ready");
$uploadCrop.croppie("bind", {
url: e.target.result
}).then(function () {
console.log("jQuery bind complete");
});
}
reader.readAsDataURL(input.files[0]);
}
else {
alert("Sorry - you're browser doesn't support the FileReader API");
}
}
</script>
</body>
</html>

Problems with responsive images in absolute positioned containers

I'm kind of stuck when trying to use this slideshow plugin:
https://github.com/iamvery/galleriffic
I'm using this because it has page pagination.
Anyway,
the problem is the container has to be position: absolute which means I must give it a height so elements below respect its height.
The problem with this is the images. I want them to be responsive.
So basically I'd like to use max-width: 100%;.
The problem is obviously if my container is for e.g 600px high and my images are responsive then my image height will decrease under that 600px and leave white space.
I've tried having img width 100% but fixed height but then they skew as your resize the browser.
I'm not sure if there is a solution.
Any ideas?
Example here:
https://jsfiddle.net/u08vrpt2/
HTML
<body>
<div class="image">
<div class="image__item">
<img src="https://s15.postimg.org/qwsiomo97/test.jpg" alt="test image">
</div>
</div>
</body>
CSS
.image {
position: relative;
max-width: 1200px;
margin: 0 auto;
height: 500px;
background: grey;
}
.image__item {
position: absolute;
top: 0;
left: 0;
}
img {
max-width: 100%;
}
Why the container needs to be absolute?
If we remove that, you still having the same behavior
.image {
position: relative;
max-width: 1200px;
background: grey;
}
img {
max-width: 100%;
display: block;
height: auto;
margin: 0 auto;
}
<div class="image">
<div class="image__item">
<img src="https://s15.postimg.org/qwsiomo97/test.jpg" alt="test image">
</div>
</div>
<p>This text respect the image height</p>

How to center image in a div horizontally and vertically

I have the following markup code in my page:
<div id="root_img" style="width:100%;height:100%">
<div id="id_immagine" align="center" style="width: 100%; height: 100%;">
<a id="a_img_id" href="./css/imgs/mancante.jpg">
<img id="img_id" src="./css/imgs/mancante.jpg" />
</a>
</div>
</div>
And it does not appear as I expected, it looks like that:
But I wanted to get this result:
How can I center this image horizontally and vertically?
Here is a tutorial for how to center the images vertically and horizontally in a div.
Here is what you are looking for:
.wraptocenter {
display: table-cell;
text-align: center;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: #999;
}
.wraptocenter * {
vertical-align: middle;
}
<div class="wraptocenter">
<img src="http://www.brunildo.org/thumb/tmiri2_o.jpg">
</div>
For vertical alignment, I would include some CSS to position it from the top 50% and then move it up half the number of pixels height of the image.
Horizontal, I would use a margin, as suggested.
So if your image was 100x100px you'd end up with.
<img id="my_image" src="example.jpg">
<style>
#my_image{
position: absolute;
top: 50%;
margin: -50px auto 0;
}
</style>
Image in a div horizontally and vertically.
<div class="thumbnail">
<img src="image_path.jpg" alt="img">
</div>
.thumbnail {
height: 200px;
margin: 0 auto;
position: relative;
}
.thumbnail img {
position: absolute;
bottom: 0;
left: 0;
right: 0;
top: 0;
margin: auto;
max-width: 100%;
max-height: 100%;
}
There are two aspects you need to address. First aspect is the horizontal alignment. This is easily achievable with the margin: auto applied on the div element surrounding the image itself. DIV needs to have width and height set to image size (otherwise this will not work). To achieve vertical center alignment you need to add some javascript to the HTML. This is because HTML height size is not known on the startup of the page and might change later on. The best solution is to use jQuery and write the following script:
$(window).ready( function() { /* listen to window ready event - triggered after page is being loaded*/
repositionCenteredImage();
});
$(window).resize(function() { /* listen to page resize event - in case window size changes*/
repositionCenteredImage();
});
function repositionCenteredImage() { /* reposition our image to the center of the window*/
pageHeight = $(window).height(); /*get current page height*/
/*
* calculate top and bottom margin based on the page height
* and image height which is 300px in my case.
* We use half of it on both sides.
* Margin for the horizontal alignment is left untouched since it is working out of the box.
*/
$("#pageContainer").css({"margin": (pageHeight/2 - 150) + "px auto"});
}
HTML page which is showing the image looks like this:
<body>
<div id="pageContainer">
<div id="image container">
<img src="brumenlabLogo.png" id="logoImage"/>
</div>
</div>
</body>
CSS attached to the elements looks like this:
#html, body {
margin: 0;
padding: 0;
background-color: #000;
}
#pageContainer { /*css for the whole page*/
margin: auto auto; /*center the whole page*/
width: 300px;
height: 300px;
}
#logoImage { /*css for the logo image*/
width: 300px;
height: 300px;
}
You can download the whole solution from our Company homepage at the following url:
http://brumenlab.com
This solution is for all size images
In this the ration of the image is also maintain.
.client_logo{
height:200px;
width:200px;
background:#f4f4f4;
}
.display-table{
display: table;
height: 100%;
width: 100%;
text-align: center;
}
.display-cell{
display: table-cell;
vertical-align: middle;
}
.logo-img{
width: auto !important;
height: auto;
max-width: 100%;
max-height: 100%;
}
<div class="client_logo">
<div class="display-table">
<div class="display-cell">
<img src="http://www.brunildo.org/thumb/tmiri2_o.jpg">
</div>
</div>
</div>
You can set size of
.client_logo
accourding to your requirement
Try something like this:
<div style="display:table-cell; vertical-align:middle">
"your content"
</div>
using margin-top
example css
#id_immagine{
margin:0 auto;
}

How do I auto-resize an image to fit a 'div' container?

How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining its width:height ratio?
Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.
Do not apply an explicit width or height to the image tag. Instead, give it:
max-width:100%;
max-height:100%;
Also, height: auto; if you want to specify a width only.
Example: http://jsfiddle.net/xwrvxser/1/
img {
max-width: 100%;
max-height: 100%;
}
.portrait {
height: 80px;
width: 30px;
}
.landscape {
height: 30px;
width: 80px;
}
.square {
height: 75px;
width: 75px;
}
Portrait Div
<div class="portrait">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Landscape Div
<div class="landscape">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
Square Div
<div class="square">
<img src="http://i.stack.imgur.com/xkF9Q.jpg">
</div>
It turns out there's another way to do this: object-fit.
<img style='height: 100%; width: 100%; object-fit: contain'/>
will do the work. Don't forget to include other necessary attributes like src and alt, of course.
Fiddle: http://jsfiddle.net/mbHB4/7364/
Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.
To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.
Choosing whether to do height or width depends on your image and container dimensions:
If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
If your image is portrait, and your container is landscape, you must set height="100%" on the image.
If your image is landscape, and your container is portrait, you must set width="100%" on the image.
If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.
You just have to ensure that the SVG file has none of these properties set in the <svg> tag:
height
width
viewbox
Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.
Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div.
The HTML content:
<div id="myDiv">
<img alt="Client Logo" title="Client Logo" src="Imagelocation" />
</div>
The CSS content:
#myDiv
{
height: 104px;
width: 140px;
}
#myDiv img
{
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
}
The jQuery part:
var logoHeight = $('#myDiv img').height();
if (logoHeight < 104) {
var margintop = (104 - logoHeight) / 2;
$('#myDiv img').css('margin-top', margintop);
}
You have two ways of making the image responsive.
When an image is a background image.
#container{
width: 300px;
height: 300px;
background-image: url(https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}
<div id="container"><div>
Run it here
But one should use img tag to put images as it is better than background-image in terms of SEO as you can write keyword in the alt of the img tag. So here is you can make the image responsive.
When image is in img tag.
#container{
max-width: 400px;
overflow: hidden;
}
img{
width: 100%;
object-fit: contain;
}
<div id="container">
<img src="https://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/>
<div>
Run it here
Make it simple!
Give the container a fixed height and then for the img tag inside it, set width and max-height.
<div style="height: 250px">
<img src="..." alt=" " style="width: 100%;max-height: 100%" />
</div>
The difference is that you set the width to be 100%, not the max-width.
You can set the image as the background to a div, and then use the CSS background-size property:
background-size: cover;
It will "Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area" -- W3Schools
Check out my solution: http://codepen.io/petethepig/pen/dvFsA
It's written in pure CSS, without any JavaScript code.
It can handle images of any size and any orientation.
Given such HTML:
<div class="image">
<div class="trick"></div>
<img src="http://placekitten.com/415/200"/>
</div>
the CSS code would be:
.image {
font-size: 0;
text-align: center;
width: 200px; /* Container's dimensions */
height: 150px;
}
img {
display: inline-block;
vertical-align: middle;
max-height: 100%;
max-width: 100%;
}
.trick {
display: inline-block;
vertical-align: middle;
height: 150px;
}
There are several ways to fit the image to <div>.
img {
object-fit: cover;
}
The CSS object-fit property is used to specify how an <img> or <video> should be resized to fit its container.
This property tells the content to fill the container in a variety of ways; such as "preserve that aspect ratio" or "stretch up and take up as much space as possible".
fill - This is default. The image is resized to fill the given dimension. If necessary, the image will be stretched or squished to fit
contain - The image keeps its aspect ratio, but is resized to fit within the given dimension
cover - The image keeps its aspect ratio and fills the given dimension. The image will be clipped to fit
none - The image is not resized
scale-down - the image is scaled down to the smallest version of none or contain
You can find out more working samples here.
I have much better solution without need of any JavaScript. It is fully responsive, and I use it a lot. You often need to fit an image of any aspect ratio to a container element with a specified aspect ratio. And having whole this thing fully responsive is a must.
/* For this demo only */
.container {
max-width: 300px;
margin: 0 auto;
}
.img-frame {
box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);
background: #ee0;
margin: 20px auto;
}
/* This is for responsive container with specified aspect ratio */
.aspect-ratio {
position: relative;
}
.aspect-ratio-1-1 {
padding-bottom: 100%;
}
.aspect-ratio-4-3 {
padding-bottom: 75%;
}
.aspect-ratio-16-9 {
padding-bottom: 56.25%;
}
/* This is the key part - position and fit the image to the container */
.fit-img {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
max-width: 80%;
max-height: 90%
}
.fit-img-bottom {
top: auto;
}
.fit-img-tight {
max-width: 100%;
max-height: 100%
}
<div class="container">
<div class="aspect-ratio aspect-ratio-1-1 img-frame">
<img src="https://via.placeholder.com/400x300" class="fit-img" alt="sample">
</div>
<div class="aspect-ratio aspect-ratio-4-3 img-frame">
<img src="https://via.placeholder.com/400x300" class="fit-img fit-img-tight" alt="sample">
</div>
<div class="aspect-ratio aspect-ratio-16-9 img-frame">
<img src="https://via.placeholder.com/400x400" class="fit-img" alt="sample">
</div>
<div class="aspect-ratio aspect-ratio-16-9 img-frame">
<img src="https://via.placeholder.com/300x400" class="fit-img fit-img-bottom" alt="sample">
</div>
</div>
You can set max-width and max height independently; the image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (for example, for a product picture on an infinite white background you can position it to center bottom easily).
This solution doesn't stretch the image and fills the whole container, but it cuts some of the image.
HTML:
<div><img src="/images/image.png"></div>
CSS:
div {
width: 100%;
height: 10em;
overflow: hidden;
img {
min-width: 100%;
min-height: 100%;
}
I just published a jQuery plugin that does exactly what you need with a lot of options:
https://github.com/GestiXi/image-scale
Usage:
HTML
<div class="image-container">
<img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg">
</div>
JavaScript
$(function() {
$("img.scale").imageScale();
});
I see that many people have suggested object-fit which is a good option. But if you want it to work in older browsers as well, there is another way of doing it easily.
It's quite simple. The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Once it is in the centre, I give to the image,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of object-fit:cover.
Here is a demonstration of the above logic.
https://jsfiddle.net/furqan_694/s3xLe1gp/
This logic works in all browsers.
The following works perfectly for me:
img{
height: 99999px;
object-fit:contain;
max-height: 100%;
max-width: 100%;
display: block;
margin: auto auto;
}
I fixed this problem using the following code:
<div class="container"><img src="image_url" /></div>
.container {
height: 75px;
width: 75px;
}
.container img {
object-fit: cover;
object-position: top;
display: block;
height: 100%;
width: 100%;
}
A simple solution is to use Flexbox. Define the container's CSS to:
.container{
display: flex;
justify-content: center;
align-items: center;
align-content: center;
overflow: hidden;
/* Any custom height */
}
Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved.
<style type="text/css">
#container{
text-align: center;
width: 100%;
height: 200px; /* Set height */
margin: 0px;
padding: 0px;
background-image: url('../assets/images/img.jpg');
background-size: content; /* Scaling down large image to a div */
background-repeat: no-repeat;
background-position: center;
}
</style>
<div id="container>
<!-- Inside container -->
</div>
As answered here, you can also use vh units instead of max-height: 100% if it doesn't work on your browser (like Chrome):
img {
max-height: 75vh;
}
I centered and scaled proportionally an image inside a hyperlink both horizontally and vertically this way:
#link {
border: 1px solid blue;
display: table-cell;
height: 100px;
vertical-align: middle;
width: 100px;
}
#link img {
border: 1px solid red;
display: block;
margin-left: auto;
margin-right: auto;
max-height: 60px;
max-width: 60px;
}
It was tested in Internet Explorer, Firefox, and Safari.
More information about centering is here.
Give the height and width you need for your image to the div that contains the <img> tag. Don't forget to give the height/width in the proper style tag.
In the <img> tag, give the max-height and max-width as 100%.
<div style="height:750px; width:700px;">
<img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>
You can add the details in the appropriate classes after you get it right.
The code below is adapted from previous answers and is tested by me using an image called storm.jpg.
This is the complete HTML code for a simple page that displays the image. This works perfect and was tested by me with www.resizemybrowser.com. Put the CSS code at the top of your HTML code, underneath your head section. Put the picture code wherever you want the picture.
<html>
<head>
<style type="text/css">
#myDiv
{
height: auto;
width: auto;
}
#myDiv img
{
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
}
</style>
</head>
<body>
<div id="myDiv">
<img src="images/storm.jpg">
</div>
</body>
</html>
You have to tell the browser the height of where you are placing it:
.example {
height: 220px; /* DEFINE HEIGHT */
background: url('../img/example.png');
background-size: 100% 100%;
background-repeat: no-repeat;
}
Edit: Previous table-based image positioning had issues in Internet Explorer 11 (max-height doesn't work in display:table elements). I've replaced it with inline based positioning which not only works fine in both Internet Explorer 7 and Internet Explorer 11, but it also requires less code.
Here is my take on the subject. It'll only work if the container has a specified size (max-width and max-height don't seem to get along with containers that don't have concrete size), but I wrote the CSS content in a way that allows it to be reused (add picture-frame class and px125 size class to your existing container).
In CSS:
.picture-frame
{
vertical-align: top;
display: inline-block;
text-align: center;
}
.picture-frame.px125
{
width: 125px;
height: 125px;
line-height: 125px;
}
.picture-frame img
{
margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
max-width: 100%;
max-height: 100%;
display: inline-block;
vertical-align: middle;
border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}
And in HTML:
<a href="#" class="picture-frame px125">
<img src="http://i.imgur.com/lesa2wS.png"/>
</a>
DEMO
/* Main style */
.picture-frame
{
vertical-align: top;
display: inline-block;
text-align: center;
}
.picture-frame.px32
{
width: 32px;
height: 32px;
line-height: 32px;
}
.picture-frame.px125
{
width: 125px;
height: 125px;
line-height: 125px;
}
.picture-frame img
{
margin-top: -4px; /* Inline images have a slight offset for some reason when positioned using vertical-align */
max-width: 100%;
max-height: 100%;
display: inline-block;
vertical-align: middle;
border: 0; /* Remove border on images enclosed in anchors in Internet Explorer */
}
/* Extras */
.picture-frame
{
padding: 5px;
}
.frame
{
border:1px solid black;
}
<p>32px</p>
<a href="#" class="picture-frame px32 frame">
<img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
<img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px32 frame">
<img src="http://i.imgur.com/BDabZj0.png"/>
</a>
<p>125px</p>
<a href="#" class="picture-frame px125 frame">
<img src="http://i.imgur.com/lesa2wS.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
<img src="http://i.imgur.com/kFMJxdZ.png"/>
</a>
<a href="#" class="picture-frame px125 frame">
<img src="http://i.imgur.com/BDabZj0.png"/>
</a>
Edit: Possible further improvement using JavaScript (upscaling images):
function fixImage(img)
{
var $this = $(img);
var parent = $this.closest('.picture-frame');
if ($this.width() == parent.width() || $this.height() == parent.height())
return;
if ($this.width() > $this.height())
$this.css('width', parent.width() + 'px');
else
$this.css('height', parent.height() + 'px');
}
$('.picture-frame img:visible').each(function
{
if (this.complete)
fixImage(this);
else
this.onload = function(){ fixImage(this) };
});
The accepted answer from Thorn007 doesn't work when the image is too small.
To solve this, I added a scale factor. This way, it makes the image bigger and it fills the div container.
Example:
<div style="width:400px; height:200px;">
<img src="pix.jpg" style="max-width:100px; height:50px; transform:scale(4); transform-origin:left top;" />
</div>
Notes:
For WebKit you must add -webkit-transform:scale(4); -webkit-transform-origin:left top; in the style.
With a scale factor of 4, you have max-width = 400/4 = 100 and max-height = 200/4 = 50
An alternate solution is to set max-width and max-height at 25%. It's even simpler.
A simple solution (4-step fix!!) that seems to work for me, is below. The example uses the width to determine the overall size, but you can also flip it to use the height instead.
Apply CSS styling to the image container (for example, <img>)
Set the width property to the dimension you want
For dimensions, use % for relative size, or autoscaling (based on image container or display)
Use px (or other) for a static, or set dimension
Set the height property to automatically adjust, based on the width
ENJOY!
For example,
<img style="width:100%; height:auto;"
src="https://googledrive.com/host/0BwDx0R31u6sYY1hPWnZrencxb1k/thanksgiving.png"
/>
All the provided answers, including the accepted one, work only under the assumption that the div wrapper is of a fixed size. So this is how to do it whatever the size of the div wrapper is and this is very useful if you develop a responsive page:
Write these declarations inside your DIV selector:
width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */
Then put these declarations inside your IMG selector:
width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */
VERY IMPORTANT:
The value of maxHeight must be the same for both the DIV and IMG selectors.
The simplest way to do this is by using object-fit:
<div class="container">
<img src="path/to/image.jpg">
</div>
.container{
height: 300px;
}
.container img{
height: 100%;
width: 100%;
object-fit: cover;
}
If you're using Bootstrap, just add the img-responsive class and change to
.container img{
object-fit: cover;
}
If you're using Bootstrap, you just need to add the img-responsive class to the img tag:
<img class="img-responsive" src="img_chania.jpg" alt="Chania">
Bootstrap Images
As seen in my 2014 Codepen example, I've made a solution that would work for any unknown combination of width/height (aspect-ratio) with the help of a as little javascript as possible, to change the CSS of how the image is centered when the aspect-ratio of the container changes above/below the aspect ratio of the image:
Try resizing the container by dragging the bottom right corner:
// Detects when the window width is too narrow for the current image
// aspect-ratio, and fits it to height 100% instead of width 100%.
const photo = document.images[0]
const onPhotoResize = new ResizeObserver(entries =>
window.requestAnimationFrame(checkRatio)
)
onPhotoResize.observe(photo.parentNode)
function checkRatio(){
const photoParent = photo.parentNode,
imageAspectRatio = photo.clientWidth / photo.clientHeight,
parentAspectRatio = photoParent.clientWidth / photoParent.clientHeight
photo.classList[imageAspectRatio > parentAspectRatio ? 'add':'remove']('max')
}
.box{
width: 20%;
height: 60%;
margin: auto;
position: absolute;
top:0; left:0; right:0; bottom:0;
resize: both;
overflow: hidden;
border: 5px solid red;
}
.box > img{
position: absolute;
top: 50%;
left: 50%;
width: 100%;
transform: translate(-50%, -50%);
}
.box > img.max{ width:auto; height:100%; }
<div class='box'>
<img src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Mona_Lisa.jpg">
</div>
The solution is easy with a bit of maths...
Just put the image in a div and then in the HTML file where you specify the image. Set the width and height values in percentages using the pixel values of the image to calculate the exact ratio of width to height.
For example, say you have an image that has a width of 200 pixels and a height of 160 pixels. You can safely say that the width value will be 100%, because it is the larger value. To then calculate the height value you simply divide the height by the width which gives the percentage value of 80%. In the code it will look something like this...
<div class="image_holder_div">
<img src="some_pic.png" width="100%" height="80%">
</div>