Is it possible to fill a div with an image such that at least one image dimension is 100% and the other dimension is either wider or equal size as the div, whilst r
You could set the images as the div's backgrounds instead and use backkground-size:cover
https://jsfiddle.net/3x5x0v24/
Consider using the CSS object-fit
property.
5.5. Sizing Objects: the object-fit property
The
object-fit
property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.Here are two of the values:
cover
The replaced content is sized to maintain its aspect ratio while filling the element's entire content box.
contain
The replaced content is sized to maintain its aspect ratio while fitting within the element's content box.
So, with cover
the image retains its aspect ratio and covers all available space. Of course, this means that much of an image may be cropped off-screen.
With contain
the aspect ratio is also maintained, but the image scales to fit within the box. This means that an image may have whitespace on the left and right, or top and bottom.
Browser Compatibility
As of this writing, object-fit is not supported by Internet Explorer. For a workaround see:
More information
Here is the solution without using background images and with HTML and CSS only: http://codepen.io/anon/pen/JGGObQ
(change overflow
to visible
in the .container1
rule to see the full pictures. The numbers in them are their original size in pixels.)
It uses position: absolute
on the images, and depending on the format (two classes, as suggested by yourself) a top
or left
of 50%
that moves the position reference into the (horizontal or vertical) center, and a transform : translate
setting that moves the position reference point of the image back from that center by 50%
of their own size, which results in centering:
.container1 {
position: relative;
float: left;
margin-right: 50px;
width: 400px;
height: 400px;
border-radius: 50%;
overflow: hidden;
border: 1px solid red;
}
img.landscape {
position: absolute;
width: auto;
height: 100%;
transform: translate(-50%, 0);
left: 50%;
}
img.portrait {
position: absolute;
width: 100%;
height: auto;
transform: translate(0, -50%);
top: 50%;
}
<div class="container1">
<img src="http://placehold.it/750x500/09d/fff" class="landscape">
</div>
<div class="container1">
<img src="http://placehold.it/600x900/0d9/fff" class="portrait">
</div>
This is not the exact solution, but it could be an implementation that you could try to make your code work. Here is an example:
As you can't predict the aspect ratio of the image here is what I would do:
HTML: Set the div tag to 'fill':
<div class="fill"></div>
CSS: This will place your image as the background, and stretch it to fit the div size without distortion.
.fill {
overflow: hidden;
background-size: cover;
background-position: center;
background-image:"path/to/image.jpg";
}