CSS force image resize and keep aspect ratio - css

I am working with images, and I ran into a problem with aspect ratios.
<img src="big_image.jpg" width="900" height="600" alt="" />
As you can see, height and width are already specified. I added a CSS rule for images:
img {
max-width: 500px;
}
But for big_image.jpg, I receive width=500 and height=600. How do I set images to be re-sized, whilst keeping their aspect ratios.

img {
display: block;
max-width:230px;
max-height:95px;
width: auto;
height: auto;
}
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
<img width="400" height="400" src="http://i.stack.imgur.com/aEEkn.png">
This will make image shrink if it's too big for specified area (as downside, it will not enlarge image).

Here's a solution:
object-fit: cover;
width: 100%;
height: 250px;
You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you.
More information about the possible values for the object-fit property and a compatibility table are available here: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

The solutions below will allow scaling up and scaling down of the image, depending on the parent box width.
All images have a parent container with a fixed width for demonstration purposes only. In production, this will be the width of the parent box.
Best Practice (2018):
This solution tells the browser to render the image with max available width and adjust the height as a percentage of that width.
.parent {
width: 100px;
}
img {
display: block;
width: 100%;
height: auto;
}
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
<div class="parent">
<img width="400" height="400" src="https://placehold.it/400x400">
</div>
Fancier Solution:
With the fancier solution, you'll be able to crop the image regardless of its size and add a background color to compensate for the cropping.
.parent {
width: 100px;
}
.container {
display: block;
width: 100%;
height: auto;
position: relative;
overflow: hidden;
padding: 34.37% 0 0 0; /* 34.37% = 100 / (w / h) = 100 / (640 / 220) */
}
.container img {
display: block;
max-width: 100%;
max-height: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
<p>This image is originally 640x220, but should get resized by the CSS:</p>
<div class="parent">
<div class="container">
<img width="640" height="220" src="https://placehold.it/640x220">
</div>
</div>
For the line specifying padding, you need to calculate the aspect ratio of the image, for example:
640px (w) = 100%
220px (h) = ?
640/220 = 2.909
100/2.909 = 34.37%
So, top padding = 34.37%.

Very similar to some answers here, but in my case I had images that sometimes were taller, sometimes larger.
This style worked like a charm to make sure that all images use all available space, keep the ratio and not cuts:
.img {
object-fit: contain;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}

The background-size property is ie>=9 only, but if that is fine with you, you can use a div with background-image and set background-size: contain:
div.image{
background-image: url("your/url/here");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
Now you can just set your div size to whatever you want and not only will the image keep its aspect ratio it will also be centralized both vertically and horizontally within the div. Just don't forget to set the sizes on the css since divs don't have the width/height attribute on the tag itself.
This approach is different than setecs answer, using this the image area will be constant and defined by you (leaving empty spaces either horizontally or vertically depending on the div size and image aspect ratio), while setecs answer will get you a box that exactly the size of the scaled image (without empty spaces).
Edit:
According to the MDN background-size documentation you can simulate the background-size property in IE8 using a proprietary filter declaration:
Though Internet Explorer 8 doesn't support the background-size property, it is possible to emulate some of its functionality using the non-standard -ms-filter function:
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";

Remove the "height" property.
<img src="big_image.jpg" width="900" alt=""/>
By specifying both you are changing the aspect ratio of the image. Just setting one will resize but preserve the aspect ratio.
Optionally, to restrict oversizings:
<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>

Firefox 71+ (2019-12-03) and Chrome 79+ (2019-12-10) support internal mapping of the width and height HTML attributes of the IMG element to the new aspect-ratio CSS property (the property itself is not yet available for direct use).
The calculated aspect ratio is used to reserve space for the image until it is loaded, and as long as the calculated aspect ratio is equal to the actual aspect ratio of the image, page “jump” is prevented after loading the image.
For this to work, one of the two image dimensions must be overridden via CSS to the auto value:
IMG {max-width: 100%; height: auto; }
<img src="example.png" width="1280" height="720" alt="Example" />
In the example, the aspect ratio of 16:9 (1280:720) is maintained even if the image is not yet loaded and the effective image width is less than 1280 as a result of max-width: 100%.
See also the related Firefox bug 392261.

Here is a solution :
img {
width: 100%;
height: auto;
object-fit: cover;
}
This will make sure the image always covers the entire parent (scaling down and up) and keeps the same aspect ratio.

Just add this to your css, It will automaticly shrink and expand with keeping the original ratio.
img {
display: block;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}

This is mental. Use the scale-down property - it explains itself.
Inline styling:
<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />
This will stop flex from stretching it. In this case, the image would go to 50% of the width of its parent container and the height would scale down to match.
Keep it simple.

Just replace the height attribute by the aspect-ratio attribute.
img {
max-width: 500px;
aspect-ratio: 900 / 600;
}
<img src="big_image.png" width="900"/>
The aspect-ratio attribute is not necessary, but prevent image layout shifts.

To maintain a responsive image while still enforcing the image to have a certain aspect ratio you can do the following:
HTML:
<div class="ratio2-1">
<img src="../image.png" alt="image">
</div>
And SCSS:
.ratio2-1 {
overflow: hidden;
position: relative;
&:before {
content: '';
display: block;
padding-top: 50%; // ratio 2:1
}
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
}
This can be used to enforce a certain aspect ratio, regardless of the size of the image that authors upload.
Thanks to #Kseso at http://codepen.io/Kseso/pen/bfdhg. Check this URL for more ratios and a working example.

Set the CSS class of your image container tag to image-class:
<div class="image-full"></div>
and add this you your CSS stylesheet.
.image-full {
background: url(...some image...) no-repeat;
background-size: cover;
background-position: center center;
}

I would suggest for a responsive approach the best practice would be using the Viewport units and min/max attributes as follows:
img{
display: block;
width: 12vw;
height:12vw;
max-width:100%;
min-width:100px;
min-height:100px;
object-fit:contain;
}

To force image that fit in a exact size, you don't need to write too many codes. It's so simple
img{
width: 200px;
height: auto;
object-fit: contain; /* Fit logo in the image size */
-o-object-fit: contain; /* Fit logo fro opera browser */
object-position: top; /* Set logo position */
-o-object-position: top; /* Logo position for opera browser */
}
<img src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png" alt="Logo">

https://jsfiddle.net/sot2qgj6/3/
Here is the answer if you want to put image with fixed percentage of width, but not fixed pixel of width.
And this will be useful when dealing with different size of screen.
The tricks are
Using padding-top to set the height from width.
Using position: absolute to put image in the padding space.
Using max-height and max-width to make sure the image will not over the parent element.
using display:block and margin: auto to center the image.
I've also comment most of the tricks inside the fiddle.
I also find some other ways to make this happen.
There will be no real image in html, so I personly perfer the top answer when I need "img" element in html.
simple css by using background
http://jsfiddle.net/4660s79h/2/
background-image with word on top
http://jsfiddle.net/4660s79h/1/
the concept to use position absolute is from here
http://www.w3schools.com/howto/howto_css_aspect_ratio.asp

You can use this:
img {
width: 500px;
height: 600px;
object-fit: contain;
position: relative;
top: 50%;
transform: translateY(-50%);
}

You can create a div like this:
<div class="image" style="background-image:url('/to/your/image')"></div>
And use this css to style it:
height: 100%;
width: 100%;
background-position: center center;
background-repeat: no-repeat;
background-size: contain; // this can also be cover

You can set the container to display: flex and align-items: center (other align-items values work too). Instead of align-items you can also set align-self on the image itself.

This will make image shrink if it's too big for specified area (as downside, it will not enlarge image).
The solution by setec is fine for "Shrink to Fit" in auto mode.
But, to optimally EXPAND to fit in 'auto' mode, you need to first put the received image into a temp id,
Check if it can be expanded in height or in width (depending upon its aspect ration v/s the aspect ratio of your display block),
$(".temp_image").attr("src","str.jpg" ).load(function() {
// callback to get actual size of received image
// define to expand image in Height
if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
$(".image").css('height', max_height_of_box);
$(".image").css('width',' auto');
} else {
// define to expand image in Width
$(".image").css('width' ,max_width_of_box);
$(".image").css('height','auto');
}
//Finally put the image to Completely Fill the display area while maintaining aspect ratio.
$(".image").attr("src","str.jpg");
});
This approach is useful when received images are smaller than display box. You must save them on your server in Original Small size rather than their expanded version to fill your Bigger display Box to save on size and bandwidth.

You Can use:-
transform: scaleX(1.2);
to change the width without changing height.
And
transform: scaleY(1.2);
to change the height without changing width
You can use this on images and video tags in html and css. This does not change the aspect ration also.

you can use aspect-ratio property css
.my-image {
aspect-ratio: 1/1; // square
aspect-ratio: 16/9; // wide screen 1080p
aspect-ratio: 4/3;
aspect-ratio: 2/3;
}

img {
max-width: 80px; /* Also works with percentage value like 100% */
height: auto;
}
<p>This image is originally 400x400 pixels, but should get resized by the CSS:</p>
<img width="400" height="400" src="https://i.stack.imgur.com/aEEkn.png">
<p>Let's say the author of the HTML deliberately wants
the height to be half the value of the width,
this CSS will ignore the HTML author's wishes, which may or may not be what you want:
</p>
<img width="400" height="200" src="https://i.stack.imgur.com/aEEkn.png">

How about using a pseudo element for vertical alignment? This less code is for a carousel but i guess it works on every fixed size container. It will keep the aspect ratio and insert #gray-dark bars on top/bottom or left/write for the shortest dimension. In the meanwhile the image is centered horizontally by the text-align and vertically by the pseudo element.
> li {
float: left;
overflow: hidden;
background-color: #gray-dark;
text-align: center;
> a img,
> img {
display: inline-block;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
margin: auto;
text-align: center;
}
// Add pseudo element for vertical alignment of inline (img)
&:before {
content: "";
height: 100%;
display: inline-block;
vertical-align: middle;
}
}

Fullscreen presentation:
img[data-attribute] {height: 100vh;}
Keep in mind that if the view-port height is greater than the image the image will naturally degrade relative to the difference.

If the application can have an image of any aspect ratio or resolution then you can manage height and width as in this link.
This uses Javascript and HTML
https://stackoverflow.com/a/65090175/13338731

Related

Scale dynamic image with different widths and heights

I have image in the header and populate its source from the database, so it has different width and height. Image dimensions could be max 2000x2000px. I'm trying to scale it but when it's very large e.g more than 1000px it's very big and it's not looking good.
This is what I currently have.
#image {
position: absolute;
display: block;
top: 20px;
left: 20px;
height: 50px;
}
<div id="wrapper">
<img src="some-dynamic-url" id="image">
</div>
I've also tried with background-size: cover but it's not stretched and how to preserve the aspect ratio and set max-width and max-height not to be so big?
Updated. My current code is the following:
#image {
display: block;
top: 20px;
left: 20px;
width: 100%;
max-width: 170px;
}
<div id="wrapper">
<img src="some-dynamic-url" id="image">
</div>
Will the height always be 50px? If not, you should remove that from your CSS and instead use height: auto;.
Also, if it starts to not look so great at 1000px by 1000px, maybe set width: 1000px; and max-width: 85%; to keep it at that width and make it responsive on smaller screens. You can adjust the max-width value to your liking or remove it.
So, the CSS would change to:
#image {
position: absolute;
display: block;
top: 20px;
left: 20px;
width: 1000px;
max-width: 85%; /* adjust as needed or remove */
height: auto;
}
Here's an example.
If I'm understanding correctly, you have a header container area where various images get populated, and sometimes the images are too big for the container and not looking good. (A screenshot would be helpful if my summary is wrong.)
The trick here is to set the image width to 100%, then set a max-width to either the image or the header container. (I picked 1200px for this example.) That ensures that your image will fill up all of the space, but not go over.
NOTE: this will cause images with widths smaller than 1200px to be stretched to fit, and may not look good either and would require some more coding to fix.
#image {
position: absolute;
display: block;
top: 20px;
left: 20px;
width: 100%;
max-width: 1200px;
}
<div id="wrapper">
<img src="https://upload.wikimedia.org/wikipedia/commons/c/cc/ESC_large_ISS022_ISS022-E-11387-edit_01.JPG" id="image">
</div>
However, if you're looking for a work-around for images that are smaller than 2000px wide, I'd suggest something like centering them with a colored background, or perhaps tiling them. Those solutions will be good for some content, and ugly for others - it depends what you images are like and how the site looks. But those are some ideas.
You may want to use the simple trick to automatically fit size with:
img { max-width: 1200px; height: auto;}
I guess 50px for height is not a must since you thought using "cover" in backround property. Also if you wish this sort of behavior from your image, you can add "object-fit: cover;".
Read more here: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
EDIT
You can also use that version of the "trick":
img { max-height: 100px; width: auto; }
Note: Using files that big for logo is not recomand. If you got access tto database you should consider save a copy to more light version with less pixels.

CSS: Make image height of viewport while keeping width 100% and cropping edges if wider than viewport

I want to create a responsive image that takes up the entire height off the viewport and scales as the viewport changes.
I know that I can set the height with this:
height: 100vmax;
However, I cannot understand how to get the image width to change and effectively crop it's edges off so that the image stays centred horizontally.
A great example of is Big Green Egg's website although they use a video and I want to use an image.
It's worth mentioning that I need to enter this code into a CMS page (Magento 2) so it will sit within a set of other DIVs.
Try to use "vh" and use text-align on the outer container to center the image:
body {
text-align: center;
}
img {
height: 100vh;
}
<img src="http://kingofwallpapers.com/sexy-girl-wallpapers/sexy-girl-wallpapers-002.jpg">
But I would recommend to use background-image instead, since it's a part of design, not a content:
* {
margin: 0;
}
.image {
position: absolute;
top: 50px;
bottom: 0;
left: 0;
right: 0;
background: #e0eaec url(http://eskipaper.com/images/mikako-zhang-5.jpg) no-repeat center center / auto 100%;
}
h1 {
line-height: 50px;
text-align: center;
}
<h1><header> goes here</h1>
<div class="image"></div>
I'd go very simple here, with a css solution based on adding only object-fit and an optional object-position, very useful when the main point for adjustment is not the center of the picture
html
<img src="https://images.unsplash.com/photo-1518453850752-056b15f0a4ea?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80">
css
img {
float: left;
width: 100%;
height: 100vh;
object-fit: cover;
object-position: 75% 75%;
}
Try to reduce the width of the picture in this JSFiddle: you will see that the focus will keep always around the dome. I suggest also to read this gem
By default, object-position: 50% 50% [i.e. the center of the picture] so in this case you don't need to specify it
NOTE - you can check their support on different browsers here

Maintain div aspect ratio according to height

I need to maintain the width of an element as a percentage of its height. So as the height changes, the width is updated.
The opposite is achievable by using a % value for padding-top, but padding-left as a percentage will be a percentage of the width of an object, not its height.
So with markup like this:
<div class="box">
<div class="inner"></div>
</div>
I'd like to use something like this:
.box {
position: absolute;
margin-top: 50%;
bottom: 0;
}
.inner {
padding-left: 200%;
}
To ensure the box's aspect ratio is maintained according to it's height. The height is fluid because of it's % margin - as the window's height changes, the box's height will too.
I know how to achieve this with JavaScript, just wondering if there's a clean CSS-only solution?
You can use an image that has the desired proportions as to help with proportional sizing (images can be scaled proportionally by setting one dimension to some value and other to auto). The image does not have to be visible, but it must occupy space.
.box {
position: absolute;
bottom: 0;
left: 0;
height: 50%;
}
.size-helper {
display: block;
width: auto;
height: 100%;
}
.inner {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(255, 255, 153, .8);
}
<div class="box">
<img class="size-helper" src="//dummyimage.com/200x100/999/000" width="200" height="100">
<div class="inner">
1. box has fluid height<br>
2. img has 2:1 aspect ratio, 100% height, auto width, static position<br>
2.1 it thus maintains width = 200% of height<br>
2.2 it defines the dimensions of the box<br>
3. inner expands as much as box
</div>
</div>
In the above example, box, inner and helper are all same size.
You can use vh units for both height and width of your element so they both change according to the viewport height.
vh
1/100th of the height of the viewport. (MDN)
DEMO
.box {
position: absolute;
height:50vh;
width:100vh;
bottom: 0;
background:teal;
}
<div class="box"></div>
There is another, more efficient way to achieve constant aspect ratio according to height.
You can place an empty svg so you dont have to load an external image.
HTML code:
<svg xmlns="http://www.w3.org/2000/svg"
height="100"
width="200"
class='placeholder-svg'
/>
CSS code:
.placeholder-svg {
width: auto;
height: 100%;
}
Change width/height to achieve desired aspect ratio.
Keep in mind, the svg might overflow.
http://www.w3.org/2000/svg is just a namespace. It doesn't load anything.
If you change placeholder-svg class to:
.placeholder-svg {
width: 100%;
height: auto;
}
then height is adjusted according to width.
Demo 1 Width is adjusted according to height and 2:1 aspect ratio.
Demo 2 same as above, but you can resize easily (uses React)
The CSS trick you wrote, works pretty well to keep ratio width / height on an element.
It is based on the padding property that, when its value is in percent, is proportional to parent width, even for padding-top and padding-bottom.
There is no CSS property that could set an horizontal sizing proportionally to the parent height.
So I think there is no clean CSS solution.
As of 2021 there is a property called aspect-ratio.
Most browsers support it
div {
border: 1px solid;
margin: 8px;
}
.box {
width: 100px;
min-height: 100px;
resize: horizontal;
overflow: auto;
}
.inner1 {
aspect-ratio: 1/1;
}
.inner2 {
aspect-ratio: 3/1;
}
<div class="box">
<div class="inner1"></div>
<div class="inner2"></div>
</div>
Run this snippet and resize the outer div manually to see the inner divs behavior
I can't find a pure CSS solution. Here's a solution using CSS Element Queries JavaScript library.
var aspectRatio = 16/9;
var element = document.querySelector('.center');
function update() {
element.style.width = (element.clientHeight * aspectRatio) + 'px';
}
new ResizeSensor(element, update);
update();
CodePen demo!

Avoid stretch on image css

I am rendering an image into a div. I want to avoid stretching of my image.
div {
height: 300px;
width: 300px;
}
img {
min-width: 300px;
min-height: 300px;
max-height: 300px;
}
My problem is that my image's width stretches. I want it to have the regular width even though parts of the image will be missing.
div {
height: 300px;
width: 300px;
overflow: hidden;
}
img {
height: 300px
max-width: none;
min-width: 300px;
}
You can achieve this with simply adding object-fit: cover;. An example might be like -
img {
height: 300px
width: 100%;
object-fit: cover;
}
I would forget setting the min-height and the max-height. Just set the height to be 300 pixels and put an overflow hidden on the div tag. That way no matter what the image size it will always stay in proportion and never go outside the boundaries of your div tag.
div { height: 300px; width: 300px; overflow: hidden; }
img { height: 300px; }
Put the image as the div background if you want to avoid stretching the easiest way (yet maintain the original width).
To make it more flexible as just using 300px use:
img {
width: 100%;
object-fit: cover;
}
Height is automatically adjusted
just specify max-width 100% and height :auto
Use max-width instead of min-width, and just set height to 300px (or only use max-height).
You can use overflow:hidden to hide any portion of the image outside of the width of the div.
div {
height: 300px;
width: 300px;
overflow: hidden;
}
img {
/*min-width: 300px;*/
height: 300px;
}
==>If you are gonna have fixed height and don't want width stretched
div {
height: 300px;
width: 300px;
overflow: hidden;
}
img {
height: 300px
}
==>If you are gonna have fixed width and don't want height stretched
div {
height: 300px;
width: 300px;
overflow: hidden;
}
img {
width: 300px
}
After giving the image a fixed height and width, I added object-fit as below:
img {
width: 300px;
height: 300px;
object-fit: contain;
}
To avoid the image from resizing use:
object-fit: none;
More about object-fit
The CSS object-fit property is used to specify how an or
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".
Object-fit Values
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.
More info and examples
I'm adding this to expand on the answers given since some of the answers given like adding width:100% height:auto" etc., will still technically stretch Images and/or make them blurry at times. Let me explain.
I work on a lot of eCommerce websites adding products etc and image stretching/blurring is always a problem. Most times, an image scaling down isn't that much of a issue, so the answers given as far as width:100%; height: auto; etc., work just fine. But there are problems when scaling up if the image's container width is larger than the image's native/normal width.
So for example, if you have an image whose width is 100px, and a div container whose width is 200px, if you add a width:100% and height: auto; to your image randomly, this won't technically "stretch" an image, but it will make it look blurry because you are stretching your image past its normal width.
To fix this, one thing i normally do is something like this, assuming on the desktop, that you have an image that you want to show at its 100% native width with no scaling/stretching/blurring whatsoever, I do something like:
img{
display:block;
margin:0px auto;
width: initial;
height: auto;
}
which keeps my images at their native width with no scaling whatsoever. But then, when an image is going to be seen on a smaller device, I add the same rule block into a media query and do something like:
#media all and (max-width: 1200px){
img{
width:100%;
height:auto;
}
}
What this is effectively saying is "Hey Image, make my image responsive from point A to point B(mobile devices), but once you go from point B to point C (small laptops to desktops where the image fits normally and doesn't need to stretch), make the width equal to its default native width".
Hope this helps. Happy coding everyone.

How to get div height to auto-adjust to background size?

How do I get a div to automatically adjust to the size of the background I set for it without setting a specific height (or min-height) for it?
There is a very nice and cool way to make a background image work like an img element so it adjust its height automatically. You need to know the image width and height ratio. Set the height of the container to 0 and set the padding-top as percentage based upon the image ratio.
It will look like the following:
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
You just got a background image with auto height which will work just like an img element. Here is a working prototype (you can resize and check the div height): http://jsfiddle.net/8m9ur5qj/
Another, perhaps inefficient, solution would be to include the image under an img element set to visibility: hidden;. Then make the background-image of the surrounding div the same as the image.
This will set the surrounding div to the size of the image in the img element but display it as a background.
<div style="background-image: url(http://your-image.jpg);">
<img src="http://your-image.jpg" style="visibility: hidden;" />
</div>
There is no way to auto adjust for background image size using CSS.
You can hack around it by measuring the background image on the server and then applying those attributes to the div, as others have mentioned.
You could also hack up some javascript to resize the div based on the image size (once the image has been downloaded) - this is basically the same thing.
If you need your div to auto-fit the image, I might ask why don't you just put an <img> tag inside your div?
This answer is similar to others, but is overall the best for most applications. You need to know the image size before hand which you usually do. This will let you add overlay text, titles etc. with no negative padding or absolute positioning of the image. They key is to set the padding % to match the image aspect ratio as seen in the example below. I used this answer and essentially just added an image background.
.wrapper {
width: 100%;
/* whatever width you want */
display: inline-block;
position: relative;
background-size: contain;
background: url('https://upload.wikimedia.org/wikipedia/en/thumb/6/67/Wiki-llama.jpg/1600px-Wiki-llama.jpg') top center no-repeat;
margin: 0 auto;
}
.wrapper:after {
padding-top: 75%;
/* this llama image is 800x600 so set the padding top % to match 600/800 = .75 */
display: block;
content: '';
}
.main {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
color: black;
text-align: center;
margin-top: 5%;
}
<div class="wrapper">
<div class="main">
This is where your overlay content goes, titles, text, buttons, etc.
</div>
</div>
I looked at some of the solutions and they're great but I think I found a surprisingly easy way.
First, we need to get the ratio from the background image. We simply divide one dimension through another. Then we get something like for example 66.4%
When we have image ratio we can simply calculate the height of the div by multiplying the ratio by viewport width:
height: calc(0.664 * 100vw);
To me, it works, sets div height properly and changes it when the window is resized.
Maybe this can help, it's not exactly a background, but you get the idea:
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://antwrp.gsfc.nasa.gov/apod/image/0903/omegacen_davis.jpg" />
<div>Hi there</div>
</div>
Pretty sure this will never been seen all the way down here. But if your problem was the same as mine, this was my solution:
.imaged-container{
background-image:url('<%= asset_path("landing-page.png") %> ');
background-repeat: no-repeat;
background-size: 100%;
height: 65vw;
}
I wanted to have a div in the center of the image, and this will allow me of that.
There is a pure CSS solution that the other answers have missed.
The "content:" property is mostly used to insert text content into an element, but can also be used to insert image content.
.my-div:before {
content: url("image.png");
}
This will cause the div to resize its height to the actual pixel size of the image. To resize the width too, add:
.my-div {
display: inline-block;
}
The recently introduced CSS aspect-ratio attribute (~2020-2021) is a great way to do this without padding hacks and is supported on all evergreen browsers.
Since we need to know the aspect ratio of the image ahead of time, and in many usecases you'll be able to predetermine the image dimension ratio ahead of time (but not always for user generated content), you can either hardcode a single style or inline the css when necessary.
aspect-ratio will calculate the height when the width is specified, based on the provided ratio (or calculate width, if the height is specified).
div {
aspect-ratio: 3 / 2; /*common ratio, like an 800*600px image */
width: 200px; /* computed height will be 133.33px, which is width/aspect-ratio */
background: red; /* so any image bleed is shown*/
background-image: url('https://images.unsplash.com/photo-1631163190830-8770a0ad4aa9?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=200&q=80');
}
<div></div>
You can do it server side: by measuring the image and then setting the div size, OR loading the image with JS, read it's attributes and then set the DIV size.
And here is an idea, put the same image inside the div as an IMG tag, but give it visibility: hidden + play with position relative+ give this div the image as background.
I had this issue and found Hasanavi's answer but I got a little bug when displaying the background image on a wide screen - The background image didn't spread to the whole width of the screen.
So here is my solution - based on Hasanavi's code but better... and this should work on both extra-wide and mobile screens.
/*WIDE SCREEN SUPPORT*/
#media screen and (min-width: 769px) {
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: cover;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
}
/*MOBILE SUPPORT*/
#media screen and (max-width: 768px) {
div {
background-image: url('http://www.pets4homes.co.uk/images/articles/1111/large/feline-influenza-all-about-cat-flu-5239fffd61ddf.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 0;
padding-top: 66.64%; /* (img-height / img-width * container-width) */
/* (853 / 1280 * 100) */
}
}
As you might have noticed, the background-size: contain; property doas not fit well in extra wide screens, and the background-size: cover; property does not fit well on mobile screens so I used this #media attribute to play around with the screen sizes and fix this issue.
This Worked For Me:
background-image: url("/assets/image_complete_path");
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover;
height: 100%;
If it is a single predetermined background image and you want the div to to be responsive without distorting the aspect ratio of the background image you can first calculate the aspect ratio of the image and then create a div which preserves it's aspect ratio by doing the following:
Say you want an aspect ratio of 4/1 and the width of the div is 32%:
div {
width: 32%;
padding-bottom: 8%;
}
This results from the fact that padding is calculated based on the width of the containing element.
Adding to the original accepted answer just add style width:100%; to the inner image so it will auto-shrink/expand for mobile devices and wont end up taking large top or bottom margins in mobile view.
<div style="background-image: url(http://your-image.jpg);background-position:center;background-repeat:no-repeat;background-size: contain;height: auto;">
<img src="http://your-image.jpg" style="visibility: hidden; width: 100%;" />
</div>
How about this :)
.fixed-centered-covers-entire-page{
margin:auto;
background-image: url('https://i.imgur.com/Ljd0YBi.jpg');
background-repeat: no-repeat;background-size:cover;
background-position: 50%;
background-color: #fff;
left:0;
right:0;
top:0;
bottom:0;
z-index:-1;
position:fixed;
}
<div class="fixed-centered-covers-entire-page"></div>
Demo: http://jsfiddle.net/josephmcasey/KhPaF/
I would do the reverse and place the image inside of the main div with a width of 100%, which will make both the div and image responsive to screen size,
Then add the content within an absolute positioned div with width and height of 100% inside of the main div.
<div class="main" style="position: relative; width: 100%;">
<img src="your_image.png" style="width: 100%;">
<div style="position: absolute; width: 100%; height: 100%; display: flex...">
YOUR CONTENT
</div>
</div>
May be this can help, it's not exactly a background, but you get the simple idea
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
<div>Hello</div>
</div>
You can do something like that
<div style="background-image: url(http://your-image.jpg); position:relative;">
<img src="http://your-image.jpg" style="opacity: 0;" />
<div style="position: absolute;top: 0;width: 100%;height: 100%;">my content goes here</div>
</div>
If you know the ratio of the image at build time, want the height based off of the window height and you're ok targeting modern browsers (IE9+), then you can use viewport units for this:
.width-ratio-of-height {
overflow-x: scroll;
height: 100vh;
width: 500vh; /* width here is 5x height */
background-image: url("http://placehold.it/5000x1000");
background-size: cover;
}
Not quite what the OP was asking, but probably a good fit for a lot of those viewing this question, so wanted to give another option here.
Fiddle: https://jsfiddle.net/6Lkzdnge/
Suppose you have some thing like this:
<div class="content">
... // inner HTML
</div>
and you want add a background to it, but you do not know the dimension of the image.
I had a similar problem, and I solved it by using grid:
HTML
<div class="outer">
<div class="content">
... // inner HTML
</div>
<img class="background" />
</div>
CSS
.outer{
display: grid;
grid-template: auto / auto;
// or you can assign a name for this block
}
.content{
grid-area: 1 / 1 / 2 / 2;
z-index: 2;
}
.background{
grid-area: 1 / 1 / 2 / 2;
z-index: 1;
}
z-index is just for placing image actually at the background, you can of course place img.background above the div.content.
NOTE: it might cause the div.content has same height of the picture, so if div.content have any children that placed according to its height, you might want set a number not something like 'auto'.
inspired by the most liked answer, I ended up coming up with a solution using min-height and 'vw' unit
I had an image in a very unusual proportion
through experimentation I ended up using
min-height: 36vw;
that value must change, according to the ratio of your image
css code used im my actual page:
background:url('your-background-image-adress') center center no-repeat;
background-size: 100%;
background-position: top center;
margin-top: 50px;
width: 100%;
min-height: 36vw;
code pen example https://codepen.io/viniciusrad/pen/GRNPXoL
Had this issue with the Umbraco CMS and in this scenario you can add the image to the div using something like this for the 'style' attribute of the div:
style="background: url('#(image.mediaItem.Image.umbracoFile)') no-repeat scroll 0 0 transparent; height: #(image.mediaItem.Image.umbracoHeight)px"
I have been dealing with this issue for a while and decided to write a jquery plugin to solve this problem.
This plugin will find all the elements with class "show-bg" (or you can pass it your own selector) and calculate their background image dimensions.
all you have to do is include this code, mark the desired elements with class="show
Enjoy!
https://bitbucket.org/tomeralmog/jquery.heightfrombg
The best solution i can think of is by specifying your width and height in percent . This will allow you to rezise your screen based on your monitor size. its more of responsive layout..
For an instance.
you have
<br/>
<div> . //This you set the width percent to %100
<div> //This you set the width percent to any amount . if you put it by 50% , it will be half
</div>
</div>
This is the best option if you would want a responsive layout, i wouldnt recommend float , in certain cases float is okay to use. but in most cases , we avoid using float as it will affect a quite of number of things when you are doing cross-browser testing.
Hope this helps :)
actually it's quite easy when you know how to do it:
<section data-speed='.618' data-type='background' style='background: url(someUrl)
top center no-repeat fixed; width: 100%; height: 40vw;'>
<div style='width: 100%; height: 40vw;'>
</div>
</section>
the trick is just to set the enclosed div just as a normal div with dimensional values same as the background dimensional values (in this example, 100% and 40vw).
I solved this using jQuery. Until new CSS rules allow for this type of behavior natively I find it is the best way to do it.
Setup your divs
Below you have your div that you want the background to appear on ("hero") and then the inner content/text you want to overlay on top of your background image ("inner"). You can (and should) move the inline styles to your hero class. I left them here so it's quick and easy to see what styles are applied to it.
<div class="hero" style="background-image: url('your-image.png'); background-size: 100%; background-repeat: no-repeat; width: 100%;">
<div class="inner">overlay content</div>
</div>
Calculate image aspect ratio
Next calculate your aspect ratio for your image by dividing the height of your image by the width. For example, if your image height is 660 and your width is 1280 your aspect ratio is 0.5156.
Setup a jQuery window resize event to adjust height
Finally, add a jQuery event listener for window resize and then calculate your hero div's height based off of the aspect ratio and update it. This solution typically leaves an extra pixel at the bottom due to imperfect calculations using the aspect ratio so we add a -1 to the resulting size.
$(window).on("resize", function ()
{
var aspect_ratio = .5156; /* or whatever yours is */
var new_hero_height = ($(window).width()*aspect_ratio) - 1;
$(".hero").height(new_hero_height);
}
Ensure it works on page load
You should perform the resize call above when the page loads to have the image sizes calculated at the outset. If you don't, then the hero div won't adjust until you resize the window. I setup a separate function to do the resize adjustments. Here's the full code I use.
function updateHeroDiv()
{
var aspect_ratio = .5156; /* or whatever yours is */
var new_hero_height = ($(window).width()*aspect_ratio) - 1;
$(".hero").height(new_hero_height);
}
$(document).ready(function()
{
// calls the function on page load
updateHeroDiv();
// calls the function on window resize
$(window).on("resize", function ()
{
updateHeroDiv();
}
});
If you can make an image on Photoshop where the main layer has an opacity of 1 or so and is basically transparent, put that img in the div and then make the real picture the background image. THEN set the opacity of the img to 1 and add the size dimensions you want.
That picture is done that way, and you can't even drag the invisible image off the page which is cool.
just add to div
style="overflow:hidden;"

Resources