How to keep a div in a certain ratio, but give it a maximum size?

I am trying to keep the div element in a specific ratio (e.g. 1: 2), but keep the width less than 200 pixels.

What I have so far:

 div { width: 100%; height: 0; padding-bottom: 50%; max-width: 200px; } 

This does not work - if I expand the window, the width stops expanding by 200 pixels, but the height grows!

I tried setting box-sizing: border-box and max-height: 100px but it doesn’t work.

What should I do?

Here's the script: http://jsfiddle.net/WVu3s/

+6
source share
2 answers

Here is a clean CSS solution based on the code from this post, but with some minor changes:

HTML

 <div class = "box"> <div class = "content">Ratio 1:2</div> </div> 

CSS

 /* Box styles */ .box { width: 100%; position: relative; display: inline-block; max-width:200px; /* max width of the box */ } .box:after { padding-top: 50%; /*1:2 ratio*/ display: block; content: ''; } /* Style that should be applied to the box content */ .content { position: absolute; width: 100%; height: 100%; top: 0; left: 0; background-color: green; } 

And here is the demo

+1
source

In my situation, the problem was that I wanted to display two different images depending on the css class applied to the body tag. I could just use display: not one on which I would not want to show, but that would require loading both when only one is needed, so I ended up like this:

HTML:

 <div class='arrow'> <img src="/img/arrow.png" style='max-width: 100%;'> </div> 

CSS:

 .arrow { max-width: 100%; overflow: auto; } .darktheme .arrow { background: url(/img/arrow-darktheme.png) center no-repeat; } .darktheme .arrow img { opacity: 0; } 

It loads both in the dark theme, but only one if the dark theme does not apply.

0
source

Source: https://habr.com/ru/post/957926/


All Articles