图像高度与宽度相同

新手上路,请多包涵

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

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

 .container {
width: 50%;
}

.container img {
  width: 100%;
  height: 400px; //this should be the same as the width value..
}
 <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>

最好没有 javascript 解决方案,但也许不可能?

原文由 Simon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 485
2 个回答

我们中的许多人已经 在评论中给了您一些提示,所以现在您应该能够创建一个 响应式广场


使图像适合正方形 以防万一您遗漏了最后一部分,下面是如何 将图像(具有任何纵横比)适合该 正方形。这也意味着,如果您的图像不是方形的,将会被裁剪。

片段:

 .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;
}
 <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>

原文由 Amaury Hanser 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您愿意使用背景图片,那么此解决方案将有效 https://codepen.io/anon/pen/jpyrwB

这将保持方形比例并使图像覆盖整个 div。如果图像宽度大于高度,它还会使图像居中并裁剪两侧。

HTML

 <div class='square-box'>
    <div class='square-content'></div>
</div>

CSS

 .square-box{
    position: relative;
    width: 50%;
    overflow: hidden;
}
.square-box:before{
    content: "";
    display: block;
    padding-top: 100%;
}
.square-content{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background-image: url(https://images.pexels.com/photos/1249588/pexels-photo-1249588.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260);
    background-position: center;
    background-size: 100% 100%;
    background-size: cover;
}

原文由 Axion 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题