Div with background-image and height auto - html

I am trying to display a div within a background-image. I have tried to do it in the same way that I would do it using an img but it does not work:
WITHIN IMG
HTML
<img class="scale" src="../../../assets/images/van-landing-2.JPG">
CSS
.scale {
max-width: 100%;
height: auto;
width: auto\9;
/* ie8 */
}
This is perfectly working. It shows an image that takes 100% of my screen and the height that should have to be proportional.
Photo
Nevertheless, when I try the same using a div it does not work. It displays nothing to cause it does not set a specific height, so It shows nothing.
WITHIN DIV
HTML
<div class="i-van"></div>
CSS
.i-van {
background-image: url("../../../assets/images/van-landing.JPG");
max-width: 100%;
height: auto;
width: auto\9;
/* ie8 */
}
Photo
How could I do it? I have tried using min-height and it shows it but just the minimum height. I would like to show it all.

The background-image property is used to add a background to an element. This means that the content with in that element is what dictates its size. Additionally, height:auto is interpreted by the elements content.
What you can try is to use height:100% providing that the parent elements also have defined height values. This will stretch the element to the tallest height and scale your background image accordingly.
If you are looking to display the image at the exact size or aspect ratio of the image itself, then the element will need to be defined with the exact width and height of the image.
From a semantics perspective however, you should decide if the image you are displaying is part of the content of your page or a decorative part of the design. In general, you should use a <img /> tag for images that are content and background-image for images that are not.
You can learn more about background-image here

You have to declare a valid height for your background div. As Maneesh has said height:auto takes the element content's height.
They key is to specify a height in vh or px.
After that you can easily place your text div inside it and set it
around with either flexbox or position absolute
Check the snippets! :)
CODE WITH FLEXBOX
body {
margin: 0;
}
.i-van {
display: flex;
align-items: center;
justify-content: center;
background-image: url(https://www.planwallpaper.com/static/images/3865967-wallpaper-full-hd_XNgM7er.jpg);
background-size: cover;
background-position: center;
max-width: 100%;
height: 100vh;
}
#div-inside {
font-size: 100px;
color: white;
}
<div class="i-van">
<div id="div-inside">
HELLO
</div>
</div>
CODE WITH POSITION ABSOLUTE
body {
margin: 0;
}
.i-van {
position: relative;
background-image: url(https://www.planwallpaper.com/static/images/3865967-wallpaper-full-hd_XNgM7er.jpg);
background-size: cover;
background-position: center;
max-width: 100%;
height: 100vh;
}
#div-inside {
position: absolute;
top: 50%;
/* position the top edge of the element at the middle of the parent */
left: 50%;
/* position the left edge of the element at the middle of the parent */
transform: translate(-50%, -50%);
/* This is a shorthand of translateX(-50%) and translateY(-50%) */
font-size: 100px;
color: white;
}
<div class="i-van">
<div id="div-inside">
HELLO
</div>
</div>

Related

How to provide adaptive full-width images with CSS background-image — or otherwise?

My site has full-width hero images. There are currently served as a CSS background-image with a single image URL that is 2000px wide. Loading one or more of these images on a small device is definitely sub-optimal. I would like to serve a 2000px image, a 1440px image, a 992px image, etc to improve page loading time on mobile.
It seems that I can use -webkit-image-set and image-set, but these only take dpi and 1x, 2x, etc. sizes, so that won't help in this case, as I understand it because this won't ever show smaller images on smaller screens. Alternately, I could serve different images with a media query, but that gets complicated fast if you want to serve images based on viewport and if a device is 2x or 3x. Or I could switch to a img tag instead and use srcset, but I have not been able to find a solution to get a full width image that scales both up and down and fills a fixed height. It seems like this should be possible with object-fit: cover, but no combination of max-width, height, max-height, etc that I have tried has worked.
Here's an example of the CSS background-image that I'm trying to make adaptive:
.hero {
display: block;
min-height: 80px;
width: 100%;
float: left;
position: relative;
padding: 0;
-webkit-background-size: cover;
background-size: cover;
background-position: center center;
background-image: url("https://place-hold.it/500x100");
}
<div style="width: 500px;"> <!-- for this example, is 100% on our page -->
<a class="hero"></a>
</div>
This is on Wordpress with Boostrap.
Here is how you can do that with a picture tag. I like using this tag because i think it gives you more control over the breakpoints.
Look it up here:
https://www.w3schools.com/tags/tag_picture.asp
/* Basic styling for body. not important */
body,
html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
/* The parent container needs to have position:relative */
.example-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
color: #fff;
}
/* The content element needs position:relative, and z-index higher than the BG element */
.example-content {
position: relative;
z-index: 10;
margin: 0;
}
/* The picture element */
.image-full,
.image-full img {
display: block;
/* Absolute position the element with full width/height, and a low z-index */
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
/* Object-fit:cover will make the image fill the space */
object-fit: cover;
object-position: center;
}
<div class="example-container">
<h2 class="example-content">Content goes here</h2>
<picture class="image-full">
<source media="(min-width:1200px)" srcset="https://i.picsum.photos/id/1002/4312/2868.jpg?hmac=5LlLE-NY9oMnmIQp7ms6IfdvSUQOzP_O3DPMWmyNxwo">
<source media="(min-width:500px)" srcset="https://i.picsum.photos/id/10/2500/1667.jpg?hmac=J04WWC_ebchx3WwzbM-Z4_KC_LeLBWr5LZMaAkWkF68">
<img src="https://i.picsum.photos/id/100/2500/1656.jpg?hmac=gWyN-7ZB32rkAjMhKXQgdHOIBRHyTSgzuOK6U0vXb1w">
</picture>
</div>

How can I set the size of my div equal to the size of background image?

I have a problem in the content inside of my container. Because I already set some method to get the height of the background image equal to my container. My problem is when I put a content inside my container it detects my invisible image that I set.
Here's my code:
<div class="parent">
<div class="hidden-image">
<img src="http://placehold.it/350x350" />
</div>
<h1>
text
</h1>
</div>
CSS:
.parent {
border: 1px solid red;
width: 350px;
height: auto;
position: relative;
display: flex;
align-items: center;
justify-content: center;
background: url('http://placehold.it/350x350');
background-repeat: no-repeat;
background-size: cover;
background-position: center center;
}
.parent img {
visibility: hidden;
width: 100%;
height: auto;
}
If you check my fiddle, the text moved to the right because I think that it is because of the image I set.
fiddle:
https://jsfiddle.net/kdu9691c/
This is because visibility: hidden doesn't remove the element from flow. It still takes up the same space it normally would, it's just invisible. You might try using position: absolute on either the image or the text div; or if the idea is just to keep the div a certain proportion to match the image, google css padded box aspect ratio for some neat workarounds. You also have the option of background-size: cover, which may be helpful depending on your particular constraints.

Image centering and sizing with CSS [duplicate]

This question already has answers here:
Horizontal center dynamic image in div with absolute position
(2 answers)
Closed 8 years ago.
I want to have a page which displays an image as large as possible but with the whole image in view, without changing the proportions of the image, and centred on the page (i.e. full height with borders either side, or full width with borders top and bottom). Is there a way to do this purely in CSS? I've tried various combinations of width/height/min-width/min-height properties and can't get it to display as I'd like.
I also want to be able to overlay a link that consists of a div with a background image, which changes on hover, the code for which is below. I want this to be positioned at the top right of the image:
HTML:
<div class="imagecontainer">
<img src='gallery/images/<?php echo $image;?>' max-height="100%" width="100%"/>
<div class="backbuttoncontainer">
<a class="gallerybackbutton" href="gallery/index.htm"></a>
</div>
</div>
CSS:
.imagecontainer{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
.backbuttoncontainer{
text-align:right;
margin-top: 10px;
margin-right: 10px;
height: 38px;
width: 100%;
display: block;
}
.gallerybackbutton{
background: url('icons/back_to_gallery.png') bottom;
display: inline-block;
height: 28px;
}
.gallerybackbutton:hover{
background-position: 0 0;
}
perhaps this is what you want : JSFIDDLE, here's how:
create a container for the image in any dimension you want (200x200 or 400x200 or 200x400 ), then put the image inside the container, with style
vertical-align: middle // to make your image centered vertically, but it's relative to the inline element, so if you don't have any text or set line-height for it's siblings, it doesn't work
max-width: 200px; // or your container width
max-height: 200px; // or your container height
// this style is used for my example with the container max-width and max-height set to 200px
then in the container add this style
text-align: center; // to make it centered horizontally
width: 200px; // for example
height: 200px; // for example
border: 1px solid red; // only to show the container in this example
line-height: 200px; // this will make the inline element in the center from 200px, or so
or another method by using pseudo element in this JSFIDDLE, you need to make a container and the image that going to be centered :
<div class="block">
<img src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-7.jpg" class="centered" />
</div>
add pseudo element to the container block
.block:before {
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; // to remove the spacing that's created by inline-block
}
and add style for the image that's going to be centered
.centered {
display: inline-block;
vertical-align: middle;
max-width: 100%;
max-height: 100%;
}
here's the explanation from css tricks: centering in the unknown
To use margin: auto you have to have a static width.
But your Image is a pixel image and will have that static width.
Just set your width of image and margin to auto:
.backbuttoncontainer{
margin:auto;
height: 38px;
width: 100px;
}
set image as background and try the following code
class-name{
background:url('1.jpg') no-repeat center center fixed ;
width:100%;
height:auto;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size:cover;
background-size: cover;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='1.jpg',sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='1.jpg',sizingMethod='scale')";

Position div tag at the bottom right of an image

I am trying to position an div element at the bottom right of an image, that is inside a container element. I set position relative to the container, and position absolute to the inner div, but it does not work. Here is the (http://jsfiddle.net/ZC84G/). Please, help.
<div class="container">
<div class="icon"></div>
<img src="/images/someImage.png" />
</div>
CSS:
body {
background-color: black;
}
.container {
position: relative;
}
.container img {
max-width: 75%;
max-height: 80%;
}
.icon{
background-image: url('http://icons.iconarchive.com/icons/iconfactory/star-wars-lego/32/Biggs-No-Helmet-icon.png');
width: 31px;
height: 31px;
position: absolute;
bottom: 5px;
right: 5px;
}
This is because by default div has block display mode, and it's width is 100% of the parent container. Try to add display: inline to .container
.container {
position: relative;
display: inline;
}
Here's the corrected jsfiddle: http://jsfiddle.net/ZC84G/4/
Your container div has no width and height set. And since a <div> is a block-level element by default, it will be set to 100% width ie expand to however much horizontal space is left.
Plus, you're also constraining your image size:
max-width: 75%;
max-height: 80%;
If you replace the img CSS with:
max-width: 75%;
max-height: 80%;
It works fine, and as expected: http://jsfiddle.net/ZC84G/3/
I've modified your CSS on the image a bit.
Basically, I set it to scale properly to the size of its container, and now it sits where I think you wanted it. The way you could find this yourself in the future would be to inspect the element by using right click from your browser, and looking at the size of the different elements to see what was expanding larger/smaller than it should.
.container img {
max-width: 100%;
height: 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>