-1

I have an image element with a width of clamp(100px, 160px, 27vw);.

I want to make the height of the element the same as its width.

I tried using the attribute value of auto but it did not work.

Is there any way to achieve it?

Below is a snippet of the code:

console.log(
  "The width of the element is",
  document.getElementById("img").offsetWidth +
  "px"
)

console.log(
  "The height of the element is",
  document.getElementById("img").offsetHeight +
  "px"
)
img {
  width: clamp(100px, 160px, 27vw);
  height: auto;
  object-fit: cover;
}
<img id="img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/488px-Apple_logo_black.svg.png?20211218170823">
iamaprogrammer
  • 115
  • 3
  • 10

1 Answers1

1

You could achieve this using aspect-ratio: 1 / 1. I've modified your code to show the result. As of this writing (June/2022), support for aspect-ratio is very good.

console.log(
  "The width of the element is",
  document.getElementById("img").offsetWidth +
  "px"
)

console.log(
  "The height of the element is",
  document.getElementById("img").offsetHeight +
  "px"
)
img {
  width: clamp(100px, 160px, 27vw);
  aspect-ratio: 1 / 1;
}
<img id="img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/488px-Apple_logo_black.svg.png?20211218170823">
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61