Kloves
Kloves

Reputation: 131

How to maintain responsive image aspect ratio?

I have an image that has 1900 of width and 1000 of height, and I'm using background-size: contain; and width: 100%; but I want div height the same of image changed height.


Example:

In 1366 screens, the image will reduce the size to fit screen size (width 100%), consequently, the image height will reduce too, so I want to get that height.


What I tried to do:

HTML:

<header>
    <section class="bg"></section>
</header>

CSS:

header .bg {
    background-image: url('header.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: calc((100vw * 1000) / 1900);
    float: left;
}

Problem: The vw is calculating with scrollbar width, and I want without, could I use the width % instead of vw?

I accept others ideas to do it, but I prefer using CSS.

Upvotes: 1

Views: 2688

Answers (1)

fubar
fubar

Reputation: 17398

The following will maintain it's aspect ratio.

The aspect ratio is calculated by dividing the height by the width:

1000 / 1900 = 0.5263

It's a little difficult to see this working in a code snippet, so here's a JSBin link that you can resize too.

.image-wrapper {
  height: 0;
  position: relative;
  padding-bottom: 52.63%; /* 1900:1000 */
}
.image-wrapper .image {
  background-image: url('http://via.placeholder.com/1900x1000');
  background-repeat: no-repeat;
  background-size: contain;
  height: 100%;
  left: 0;	  
  position: absolute;
  top: 0;	
  width: 100%;	
}
<div class="image-wrapper">
    <div class="image"></div>
</div>

Upvotes: 2

Related Questions