需要图像响应完全响应方形区域

Need image to responsively fill responive square area

这是我的 jsfiddle 代码。

<div class="gallery-thumbnail">
    <a href="google.com">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/13Vend%C3%A9miaire.jpg/1024px-13Vend%C3%A9miaire.jpg" />
    </a>
</div>

.gallery-thumbnail {
    display: flex;
    max-width: 400px;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    background: silver;
}
.gallery-thumbnail a { /* This magic makes a square, because the padding % is of the element's width. */
    height: 0;
    padding-bottom: 100%;
}
.gallery-thumbnail img {
  position: relative;
  object-fit: cover;
  width: 100%;
  background-color: green;
}

https://jsfiddle.net/hgw7s9qf/

我花了一段时间搜索如何为所有屏幕尺寸制作一个正方形元素,然后又花了一些时间尝试在该区域内设置一个不完全正方形的图像。我发现我不能一次拥有所有东西。

我怎样才能使该图像响应式地适合填充正方形,即人们期望 object-fit: cover 工作的方式,同时仍将该区域保持为动态调整大小的正方形?

重要提示:我需要它具有响应性,因此正方形会像 window 那样缩小,里面的图像也应该如此。

我不完全确定你的最终目标是什么,但使用相同的标记,我可以让它工作:

.gallery-thumbnail {
    max-width: 400px;
    background: red;
}
.gallery-thumbnail img {
  display: block;
  object-fit: cover;
  width: 100%;
  height: 400px;
}

阅读 this 后,我认为图像需要 widthheight 才能使 object-fit 发挥其魔力,因为它适合 图片尺寸调整。

希望对您有所帮助。

要使图像正确正方形,您需要为图像指定相同的高度和宽度。你可以这样试试

<div class="square">
  <div class="content">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/13Vend%C3%A9miaire.jpg/1024px-13Vend%C3%A9miaire.jpg" alt="">
  </div>
</div>

.square {
    border: 5px solid red;
    text-align: center;
    width: 50vw;
    height: 50vw;
  }

.content {
}
.content img{
  height: 50vw;
  width: 50vw;
}

工作Fiddle

Square Image

我找到方法了。

我不太确定它为什么有效。也许你们中的一位聪明人可以提供帮助。

.gallery-thumbnail {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
}
.gallery-thumbnail img {
    position:absolute;
    object-fit: cover;
    width:100%;
    height:100%;
}

https://jsfiddle.net/7f13rnvu/