【问题标题】:how to show image in aspect ratio? [duplicate]如何以纵横比显示图像? [复制]
【发布时间】:2021-09-08 03:34:03
【问题描述】:

我正在使用 css 网格。我想使用纵横比显示我的图像。 取决于宽度我想显示图像。我不想给出高度的硬线值。是否可以在不给出高度的情况下显示图像。?换句话说,我取决于我想要的宽度显示图像而不给出任何高度值。

这是我的代码

https://codesandbox.io/s/condescending-flower-m616l?file=/index.html

          .abc {
            display: grid;
            grid-template-columns: repeat(12, 6.697%);
            grid-template-rows: 18px repeat(4, 1fr);
            border: 1px solid green;
            height: 320px;
          }
          .one {
            grid-column: 2/5;
            grid-row: 3/5;
            border: 1px solid;
          }
          .two {
            grid-row: 1/5;
            grid-column: 2/5;
            border: 1px solid #ee0;
          }
          .two div {
            max-width: 100%;
            /* height: 100%; */
          }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Static Template</title>
        
      </head>
      <body>
        <div class="abc">
          <div class="one">
            <p>
              Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptates
              culpa iste facaudantium Lorem ipsum,
            </p>
          </div>
          <div class="two">
            <div style="background-image: url('hero.png');"></div>
          </div>
        </div>
      </body>
    </html>

我给 /* height: 100%; */ 然后只显示我的图像?

【问题讨论】:

  • 改用transform: scale();
  • 从您的代码中,div 1 和 2 相互重叠,我们应该在图像上看到文本吗?也许预期结果的屏幕可以解释您正在尝试实现的目标以及失败的原因(您的代码中也可能缺少背景大小 + 纵横比。

标签: javascript html css image


【解决方案1】:

使用 CSS aspect-ratio 属性为图像的 div 设置纵横比。

.two div {
  aspect-ratio: 1 / 1;
  background-size: cover;
}

虽然在撰写本文时aspect-ratio 尚未得到所有 主要浏览器的支持。 caniuse.com - aspect-ratio.

作为后备,使用带有伪元素的填充技巧。

@supports not (aspect-ratio: 1 / 1) {
  .two {
    position: relative;
  }

  .two::before {
    content: "";
    display: block;
    padding-top: 100%; /* This will give it the same height as width. */
  }

  .two div {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}

【讨论】:

  • 背景尺寸也可能是一把;)
  • @G-Cyrillus,你是对的。我奇怪地认为它已经在那里了。
猜你喜欢
  • 1970-01-01
  • 2020-08-29
  • 2018-11-02
  • 2017-05-24
  • 2023-03-25
  • 2018-10-25
  • 2019-04-02
  • 1970-01-01
  • 2015-01-26
相关资源
最近更新 更多