首页 > 解决方案 > CSS:防止从扩展外部网格项设置为 1:1 纵横比的元素

问题描述

我试图阻止图像延伸到高度设置为 0 且 padding-top 为 100% 以保持 1:1 纵横比的网格项的边界之外。使用<img>元素(左侧)时效果很好,但不使用<picture>元素(右侧)。

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr
}

.item {
  display: block;
  position: relative;
  padding-top: 100%;
  height: 0;
  background-color: grey;
  border: 1px solid black;
}

.inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-rows: minmax(20px, 1fr) auto auto minmax(20px, 1fr);
}

.text {
  grid-row-start: 2;
  text-align: center;
  margin-top: 0;
  margin-bottom: 15px;
}

.img {
  grid-row-start: 3;
  max-height: 100%;
  width: auto;
  max-width: 100%;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<ul class="grid">
  <li class="item">
    <div class="inner">
      <p class="text">Text</p>
      <img class="img" src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
    </div>
  </li>
  <li class="item">
    <div class="inner">
      <p class="text">Text</p>
      <picture class="img">
        <source srcset="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80 1x, https://images.unsplash.com/photo-1618236507249-9960f2c6a53d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80 2x"
          media="(min-width: 360px)">
        <img src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
      </picture>
    </div>
  </li>
</ul>

标签: css

解决方案


也给 img 放一个类。

<img src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />

<img class="img" src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />

将溢出:自动添加到类img

小提琴


推荐阅读