There is a container with specified dimensions in which there will be some element with previously unknown dimensions. That is, the width can be greater or vice versa the height, but it should occupy the entire space of the parent without changing the proportions. Is it possible to make this element adaptive in size like the method with background-image: ... + background-size: cover , without js ?

  • I know only for one of the directions: ru.stackoverflow.com/a/480185/178988 - Qwertiy
  • @Qwertiy, one direction, this is width: 100%; height: auto; width: 100%; height: auto; or vice versa. Probably you can’t do that, not the first time I’m looking for something like this and have never found it. - user220409
  • In fact, width in percent as much as necessary and instead of height use padding-top . But how to take the height of the basis, until he came up with. - Qwertiy
  • Well, with the help of svg you can. - Qwertiy

1 answer 1

For example, on the absolute:

 .wrap { max-width: 400px; min-height: 300px; height: 100%; position: relative; border: 1px solid #ccc; } .box { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: #eee; } 
 <div class="wrap"> <div class="box"> Внутренний блок </div> </div> 

Or option with flex:

 .wrap { max-width: 400px; min-height: 300px; height: 100%; border: 1px solid #ccc; display: flex; flex-flow: row nowrap; align-items: stretch; align-content: stretch; justify-content: center; } .box { width: 100%; background: #eee; } 
 <div class="wrap"> <div class="box"> Внутренний блок </div> </div> 

+ option for your comment):

 .wrap { max-width: 400px; min-height: 300px; height: 100%; max-height: 300px; overflow: hidden; position: relative; border: 1px solid #ccc; } .box { position: absolute; top: 50%; left: 50%; right: 0; bottom: 0; background: #eee; transform: translateY(-50%) translateX(-50%); } img { max-width: 100%; width: 100%; height: auto; } @media screen and (max-width: 400px){ .box { height: 100%; } } 
 <div class="wrap"> <img class="box" src="http://co.forum4.ru/uploads/0003/cd/5c/5095-5-f.png" alt=""> </div>