1

I have an image which i want to display in the same ratio no matter what the screen size is. I want the image to take about 80% of the screen width and then the height should be calculated by itself so the image renders in ratio 4:3. I know there are similar question on Stack-overflow but so far non of them has helped me(especially those padding-top ones). Any help would be really appreciated.

.tile-clients { 
  margin-top: 0px;
  text-align: center;
  padding: 0px 0px 0px 0px;
  min-height: 400px;
  max-height: 400px;
  width: 100%;

}

.clients {
  background: url("../images/clients.jpg"); 
  background-repeat: no-repeat;
  background-size: 100% 100%;
  min-width: 400px;
  min-height: 300px;
  width: 80%;
  margin: auto;
}


<section class = "tile-clients">
  <h2>Our Clients</h2>
  <div class = "clients"></div>
</section>
lag
  • 520
  • 2
  • 10
  • 26
  • 1
    Use `80vw` instead of `80%` - This will always give a width that is 80% of the current window size – MattHamer5 Oct 21 '19 at 13:45
  • is everything else in css right for what i want to achieve? – lag Oct 21 '19 at 13:48
  • Possible duplicate of [Maintain the aspect ratio of a div with CSS](https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css) – Rob Oct 21 '19 at 14:17

2 Answers2

1

Define width like 80vw and calculate height using calc function. I have created a basic demo for this below:

.tile-clients { 
  margin: 0px auto 0px;
  text-align: center;
  padding: 0px 0px 0px 0px;
  width: 80vw;
  height: calc(80vw * 0.75); 
/* 3/4 = 0.75   */
}

.clients {
  background: url("https://source.unsplash.com/neBHai7g9vc/800x600"); 
  background-repeat: no-repeat;
  background-size: 100% 100%; */
  width: 100%;
  height: 100%;
}
<section class = "tile-clients">
  <h2>Our Clients</h2>
  <div class="clients">
  </div>
</section>

Codepen

MattHamer5
  • 1,431
  • 11
  • 21
-1

You must put .padding-top: 75%; in your css,

.clients {
  background: url("../images/clients.jpg"); 
  background-repeat: no-repeat;
  background-size: 100% 100%;
  min-width: 400px;
  min-height: 300px;
  width: 80%;
  margin: auto;
  padding-top: 75%; //4:3 css calc aspect ratio, formula: height/width*100
}
FiReFox
  • 59
  • 2
  • 9