Home > Net >  how to keep aspect ratio while resizing in css?
how to keep aspect ratio while resizing in css?

Time:06-12

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 >
  <div  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 >
  <div ></div>
</div>

But when you resize this one it does not keep the aspect ratio like in the previous one with the image
enter image description here

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

CodePudding user response:

try

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

CodePudding user response:

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 >
  <div ></div>
</div>

  • Related