简体   繁体   中英

how to keep aspect ratio while resizing in css?

I'm trying to keep the aspect ratio while resizing div like this:

 .item { display: flex; flex-direction: column; position: absolute; background-color: white; height: 20rem; width: 20rem; min-height: 10rem; min-width: 10rem; background-color:green; resize: both; overflow: hidden; } .item_img { position: relative; display: inline-block; width: 100%; height: 100%; background-image: url(https://i.ibb.co/NYCtjSn/unknown.png); background-repeat: no-repeat; background-size: contain; }
 <div class="item"> <div class="item_img" draggable="false"></div> </div>

but I'm trying to replace the image with pure css instead of having to keep a link to load image:

 .item { display: flex; flex-direction: column; position: absolute; background-color: green; height: 20rem; width:20rem; min-height: 10rem; min-width: 10rem; resize: both; overflow: hidden; } .item_img { position: relative; display: inline-block; width: 100%; height: 100%; } .unknown_icon { height: 100%; width: 100%; background-color: gray; position: relative; overflow: hidden; } .unknown_icon::before { content: ""; position: absolute; height: 35%; width:35%; border-radius: 50%; top: 30%; left: 50%; transform: translate(-50%, -50%); background-color: white; } .unknown_icon::after { content: ""; position: absolute; height: 80%; width: 80%; border-radius: 50%; top: 100%; left: 50%; transform: translate(-50%, -50%); background-color:white; }
 <div class="item"> <div class="item_img unknown_icon"></div> </div>

But when you resize this one it does not keep the aspect ratio like in the previous one with the image
在此处输入图像描述

How do I solve this problem? perhaps with aspect-ratio ?

try

.item_img {
  position: relative;
    display: inline-block;
    width: 100%;
    height: auto;
}

Use aspect-ratio . Although it be irregular after resizing:

 .item { display: flex; flex-direction: column; position: absolute; background-color: green; height: 20rem; width: 20rem; min-height: 10rem; min-width: 10rem; resize: both; overflow: hidden; } .item_img { position: relative; display: inline-block; width: 100%; height: 100%; } .unknown_icon { height: 100%; width: 100%; background-color: gray; position: relative; overflow: hidden; } .unknown_icon::before { content: ""; position: absolute; aspect-ratio: 1 / 1; /* here */ width: 35%; border-radius: 50%; top: 30%; left: 50%; transform: translate(-50%, -50%); background-color: white; } .unknown_icon::after { content: ""; position: absolute; aspect-ratio: 1 / 1; /* here */ width: 80%; border-radius: 50%; top: 100%; left: 50%; transform: translate(-50%, -50%); background-color: white; }
 <div class="item"> <div class="item_img unknown_icon"></div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM