将一个 div 调整为容器中最大可能的正方形大小

7
如何使用CSS将div调整为其容器中最大的正方形?如果CSS无法实现,如何使用JavaScript实现?
如果容器的高度大于宽度,则希望正方形的大小为“宽度x宽度”。如果容器的宽度大于高度,则希望正方形的大小为“高度x高度”。
当容器的尺寸发生变化时,子元素的尺寸应相应调整。
我发现这个答案对于保持子元素的纵横比很有帮助。当容器的宽度大于高度时,此方法不起作用,因为子元素会溢出父元素,如下面的代码片段所示。

.flex {
  display: flex;
}

.wide,
.tall {
  flex: none;
  border: 3px solid red;
}

.wide {
  width: 150px;
  height: 100px;
}

.tall {
  width: 100px;
  height: 150px;
}

div.stretchy-wrapper {
  width: 100%;
  padding-bottom: 100%;
  position: relative;
  background: blue;
}

div.stretchy-wrapper>div {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  color: white;
  font-size: 24px;
  text-align: center;
}
<div class="flex">
  <div class="wide">
    <div class="stretchy-wrapper">
      <div>Wide container</div>
    </div>
  </div>
  <div class="tall">
    <div class="stretchy-wrapper">
      <div>Tall container</div>
    </div>
  </div>
</div>


你想让哪个div变成正方形?你的当前示例有什么问题吗? - Stickers
1
你可能可以使用 vmin https://jsfiddle.net/mkfLjmgz/,但不确定你的实际情况是什么。 - Stickers
@Pangloss 刚刚在我发帖后看到了你的解决方案,发出来吧,你有我的支持 :) - Asons
我最终使用了Resize Observer,通过这个 polyfill - Sean Kuhlman
当一个大面板被添加到页面上并且图像容器的大小发生变化时,我需要调整大小。这里的解决方案是在窗口调整大小时进行调整,我认为这意味着整个浏览器窗口。 - Sean Kuhlman
显示剩余6条评论
1个回答

0
  • 使用map()获取所有.stretchy-wrapper和其父元素的宽度和高度。
  • 现在使用for循环将最大值分配给其父元素。
  • 然后$(window).resize,每当浏览器窗口大小改变时调用resizeDiv函数。

$(document).ready (function () {
  function resizeDiv () { 
    var stretchyWrapper = $(".stretchy-wrapper"),
      sWrapperWidth = stretchyWrapper.map (function () {
        return $(this).width ();
      }),
      sWrapperHeight = stretchyWrapper.map (function () {
        return $(this).height ();
      }),
      container = stretchyWrapper.map (function () {
        return $(this).parent ();
      });
    
    for (var i in container) {
      var maxVal = Math.max (sWrapperWidth[i], sWrapperHeight[i]);
      $(container[i]).css ({"width": maxVal, "height": maxVal});
    }
  }
  resizeDiv ();
  
  $(window).resize (function () {
    resizeDiv ();
  });
});
.flex {
  display: flex;
}

.wide,
.tall {
  flex: none;
  border: 3px solid red;
}

.wide {
  width: 150px;
  height: 100px;
}

.tall {
  width: 100px;
  height: 150px;
}

div.stretchy-wrapper {
  width: 100%;
  padding-bottom: 100%;
  position: relative;
  background: blue;
}

div.stretchy-wrapper>div {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  color: white;
  font-size: 24px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
  <div class="wide">
    <div class="stretchy-wrapper">
      <div>Wide container</div>
    </div>
  </div>
  <div class="tall">
    <div class="stretchy-wrapper">
      <div>Tall container</div>
    </div>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接