首页 > 解决方案 > 如何以纵横比显示图像?

问题描述

我正在使用 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%; */只给我的图像显示?

标签: javascripthtmlcssimage

解决方案


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

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

尽管在撰写本文时aspect-ratio尚未得到所有主要浏览器的支持。caniuse.com - 纵横比

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

@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%;
  }
}

推荐阅读