图像高度与宽度相同

Sim*_*mon 1 html css sass

我在容器内有一个图像,我希望它是一个完美的正方形。我将宽度设置为容器的100%,目标是height使图像的宽度与宽度相同,因为我不知道由于响应式设计,容器的尺寸将是多少。

有任何想法吗?我正在使用sass,如果有帮助的话。

.container {
width: 50%;
}

.container img {
  width: 100%;
  height: 400px; //this should be the same as the width value..
}
Run Code Online (Sandbox Code Playgroud)
<div class="container"><img src="https://images.pexels.com/photos/1249588/pexels-photo-1249588.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/></div>
Run Code Online (Sandbox Code Playgroud)

最好没有javascript解决方案,但也许不可能做到这一点?

Ama*_*ser 7

我们中的许多人在评论中给了你一些提示,因此到现在,你应该可以建立一个响应正方形


使图像适合正方形

以防万一您遗漏了最后一部分,这是如何将图像(具有任何长宽比)适合该正方形的方法。这也意味着如果图像未平方,则会被裁剪。

片段:

.container {
  position: relative;
  width: 37%; /* The size you want */
}
.container:after {
  content: "";
  display: block;
  padding-bottom: 100%; /* The padding depends on the width, not on the height, so with a padding-bottom of 100% you will get a square */
}

.container img {
  position: absolute; /* Take your picture out of the flow */
  top: 0;
  bottom: 0;
  left: 0;
  right: 0; /* Make the picture taking the size of it's parent */
  width: 100%; /* This if for the object-fit */
  height: 100%; /* This if for the object-fit */
  object-fit: cover; /* Equivalent of the background-size: cover; of a background-image */
  object-position: center;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <img src="https://images.pexels.com/photos/1249588/pexels-photo-1249588.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"/>
</div>
Run Code Online (Sandbox Code Playgroud)