【问题标题】:How do you make the height of an element the same as the width of an element which was calculated using clamp in CSS? [duplicate]如何使元素的高度与使用 CSS 中的钳位计算的元素的宽度相同? [复制]
【发布时间】:2022-06-24 23:24:00
【问题描述】:

我有一个宽度为clamp(100px, 160px, 27vw); 的图像元素。

我想让元素的高度和宽度一样。

我尝试使用auto的属性值,但没有成功。

有什么方法可以实现吗?

下面是sn-p的代码:

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">

【问题讨论】:

    标签: html css dimensions clamp


    【解决方案1】:

    您可以使用aspect-ratio: 1 / 1 实现此目的。我已经修改了您的代码以显示结果。

    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">

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2021-01-25
      相关资源
      最近更新 更多