Placing image inside a Div - html

I'm trying to place an image inside of a div, but when I do so it doesn't display at all. I've created the image myself and made the div to fit. Currently with max-width and max-height I can get it to display inside the box but only at a fraction of the size.
My current code is...
HTML
<div id="carousel">
<img src="Images/carousel1.png" alt="#" style="max-height:100%; max-width:100%;">
</div>
CSS
#carousel {
width: 1280px;
height: 300px;
border: 1px, #000;
border-style: solid;
margin: auto;
margin-top: 10px;
}

First, be sure that the path to the image is correct. Check the console and see if you have any errors.
Than, remove the inline style on the img tag and add in the css file:
#carousel img {
width: 100%;
height: auto;
}

You will need to apply the width: 100% and height 100% to your image tag and not only your container div.
check this out : http://codepen.io/anon/pen/jqzXoR

Related

Why does adding padding to an img leave a border in the image, yet padding on a div does not when using CSS background URL?

Why does this using the img tag force a white border? I've tried border:0; with but a white border is still there in the picture. This does not happen when you use div though. And is there anyway to get rid of it? See my example below:
div {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
.image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
<img class="image">
<br>
<div></div>
The answer is simple, you are wrongly using the img tag because:
src
The image URL. Mandatory for the element
And
If an error occurs while loading or rendering an image, and an onerror event handler has been set on the error event, that event handler will get called. This can happen in a number of situations, including:
The src attribute is empty ("") or null.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
So you are falling into the error case where the browser will decide to output something related to the error that you cannot really control.
If you add alt you will get another output:
div {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
.image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
<img class="image" alt="image">
<br>
<div></div>
I don't see the purpose of doing this with img but if you insist on placing a background image inside consider having a valid url of an image. Even an empty SVG will do it
div {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
.image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
}
<img class="image" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'></svg>" alt="image">
<br>
<div></div>
Why would you want to set a background image for an img element? For an img element, you could just use the src attribute instead to set its image. (I fail to see the need for setting an image's background image.)
So for rendering images, I would personally:
Use an img element and set the (required!) src attribute. This would be my preference if the image is part of the web page's (dynamic) functional/informational content. It would be included when copying/pasting data from the web site.
Use a div element with a CSS background image. This would be my preference if the image is part of the web page's (static) design. It would be ignored when copying/pasting data from the web site.
.background-image {
background: url("https://www.w3schools.com/html/pic_trulli.jpg");
width: 100px;
height: 150px;
padding: 10px;
box-sizing: border-box; /* do not size by content, but by border */
}
.image {
object-fit: none; /* do not resize image */
object-position: left top; /* do not center image */
width: 100px;
height: 150px;
}
<img class="image" src="https://www.w3schools.com/html/pic_trulli.jpg">
<br>
<div class="background-image"></div>
Instead of using border: 0;, use border: none;.
You can also try using box-sizing: border-box; to set the padding and margin inside of the element so that the total width/height is the exact total instead of having to add borders, padding, and margin to the equation.
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#:~:text=border%2Dbox%20tells%20the%20browser,to%20absorb%20that%20extra%20width.
border-box tells the browser to account for any border and padding in
the values you specify for an element's width and height. If you set
an element's width to 100 pixels, that 100 pixels will include any
border or padding you added, and the content box will shrink to absorb
that extra width.

HTML display bottom left quarter of the image

I'm a beginner in HTML coding and I'm trying to display just a part of an image. I'm displaying the image this way:
<img id="theImg" style="width:100%;" src="https://'myimage.jpg'" />
but I really don't know how to display just bottom left quarter of the image. It is even possible without making a new picture with the cropped image?
If you know the size of your image, you can put it into a container which has half the width and height of the image and use position: absolute; and the settings shown below:
.container {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
}
.container img {
position: absolute;
bottom: 0;
left: 0;
}
<div class="container">
<img src="http://placehold.it/600x400/fa0" />
</div>
You can just use a div element that has a background image and then just apply a few css changes to that div like so:
#theImg {
height: 200px;
width: 200px;
display: block;
background-image: url('https://myimage.jpg');
background-position: bottom left;
}
JsFiddle: https://jsfiddle.net/kekwdy2L/3/
Use background-image with background-position:
#my-image {
background-image: url('https://i0.wp.com/lovecuteanimals.objects.cdn.dream.io/wp-content/uploads/2016/01/Cute-Netherland-Dwarf-Rabbit.jpg?w=1160');
background-position: -220px -80px;
display: inline-block;
width: 200px;
height: 200px;
}
<div id="my-image"></div>
<style>
div {
height: height you want;
width: width you want;
background-image:url("image you want");
</style>
<div class="div"></div>
If you know the size of the image in pixels, you can use a css clip.
Note, clip is officially deprecated in css specification, however its replacement clip-path currently has very low browser support.
Another way of achieving crop is placing the <img> tag within a <div> as shown in this answer.

Make image within div responsive css

I have a image on div. The image is dynamic added via CMS.
<div class="banner_page">
<img src="banner.jpg" />
</div>
CSS:
.banner_page{
height: 200px !important;
left: 50%;
max-width: 1920px !important;
top: 0;
position: relative;
margin-left: -993px;
width: 100% !important;
}
Once I start squeezing the browser the image exceeds the horizontal bar and I need to scooll horizontally to view the image. How can I make it responsive?
Add the CSS:
.banner_page img{
width:100%;
}
This will restrict the img width to the same as that available for the parent element, .banner_page_img
Demo Fiddle
Try using .banner_page img { width: 100%; } as then it'll fill it's parent
If you also want to constrain proportions add this :
.banner_page img{
width: 100%;
height: auto;
}

Wrapping div is not resized when inner image scales (a result of window resize)

I want my images to resize as the window height changes while keeping the containing div shrink wrapping the image. I tried using:
<div>
<img src="http://akamaicovers.oreilly.com/images/9780596806767/cat.gif" alt="">
</div>
html, body {
height: 100%;
width: 100%;
}
div {
height: 90%;
background-color: black;
display: inline-block;
}
img {
height: 100%;
width: auto;
}
But it doesn't seem to work as expected. The div doesn't shrink. It actually does once I play around with the css properties in debugger.
Here is the fiddle (try resizing the result panel)
Update:
Now this is strange. Since I first posted this question the browser behaviour changed. Originally (Chrome) when I resized the window the image would shrink proportionally as expected but the wrapping div would keep its original width. What happens now (Chrome update?) is that the image doesn't shrink horizontally, and the div also.
I tried it with the latest Safari and Firefox. Both shrink the image but keep original div width. So please be kind to check your solutions on other browsers as well.
Update #2:
The div has to stay of block type as I need to place other elements in the corners of the image.
I guess you'll have to resort to JavaScript:
$(window).on('resize', function (){
$('div').width($('img').width());
});
JSFIDDLE
You just have to keep your image max-height to be 100%. Thats it.
Here is the Working Solution
The HTML:
<div>
<img src="http://akamaicovers.oreilly.com/images/9780596806767/cat.gif" alt="">
</div>
The CSS:
html, body {
height: 100%;
width: 100%;
}
div {
height: 90%;
background-color: black;
display: inline;
}
img {
max-height: 100%;
max-width: 100%;
height: 100%;
}
EDIT
Updated CSS for the img class to make the image fit the full div.
Here is the working solution for the edit.
img {
max-height: 100%;
max-width: 100%;
height: 100%;
display:block;
}
Hope this Helps.
I have had a bit of a go at your fiddle but I don't think browsers will change the width of a div based on the width of the image inside it changing its width, I have tried a few things but couldn't get it to work.
I can however suggest another approach to placing elements in the corners of your auto re-sizing image. Instead of placing these elements inside a div which is also holding the image, you could just float the image and float some div's with a fixed width to the right and the left of the image, and then make those div's cut into the image by setting some negative margins on them.
Here's an example jsFiddle demonstrating this approach. You'll see that the images stay in the corners of the main image when you resize the result window (and thereby changing the size of the main image).
HTML
<div class="right">
<img src="..." />
<img src="..." />
</div>
<img src="http://akamaicovers.oreilly.com/images/9780596806767/cat.gif" alt="" />
<div class="left">
<img src="..." />
<img src="..." />
</div>
CSS
html, body {
height: 100%;
width: 100%;
}
img {
height: 90%;
float: left;
}
div {
float: left;
width: 40px;
position: relative;
z-index: 1;
height: 90%;
}
div.left {
margin-left: -40px;
}
div.right {
margin-right: -40px;
}
div > img {
padding: 3px;
border: 2px dashed blue;
width: 30px;
height: 30px;
}
div > img:last-child {
bottom: 0px;
right: 0px;
position: absolute;
}
you want to give your image width to 100%. Use this.
img {
height: 100%;
width: 100%;
}
When you provide a width and height for the div in %, it resizes according to the page size. And the image size in % is relative to the div width and height. I have kept the div height at 90% of the available space and width at 50%. The image is at 90% both height and width, so that you can see the re-sizing of both image and div sections.
html, body {
height: 100%;
width: 100%;
}
div {
height: 90%;
background-color: black;
width:50%;
}
img {
height: 90%;
width: 90%;
}
You have to update your css written for image purpose
img {
max-height: 100%;
max-width:100%;
}
If I understood correctly, you want to resize image by height but keep proportional size?
If so, use this:
img {
height: 100%;
display: inline-block;
}
You might want to use display: block; as well, depending on your needs.
FIDDLE: http://jsfiddle.net/zhyv9/38/
I have updated the fiddle, with the Img tag self close that may cause error some times..,
and If the image have specified size height and width then it will also resize, and the corresponding div height increases/decrease as 90% when I zoom-in/zoom-out
I hope this is the answer, as I have understood wrapping and re-sizing,
Please reply if not working..
Adding this little hack worked for me. To my understanding it forces the browser to redraw/reflow its contents. Fiddle. I can't figure out why this isn't done automatically by the browser. Tested on Firefox, Chrome and Safari.
window.onresize = function() {
$(".thumb").each(function() {
this.style.display = "none";
this.offsetWidth;
this.style.display= "inline-block";
})
}

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>