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

Sea*_*man 6 html javascript css css3 flexbox

如何使用CSS将div调整为其容器中最大的可能方块?如果CSS无法实现,那么如何使用JavaScript呢?

如果容器有height > width我希望广场的大小width x width.如果容器有width > height我想要的大小正方形height x height.

当容器的尺寸改变时,儿童的尺寸应相应地调整.

我发现这个答案有助于维持孩子的长宽比.当容器的宽度大于子容器溢出父级时的高度时,此方法不起作用,如下面的代码片段所示.

.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

小智 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 ();
  });
});
Run Code Online (Sandbox Code Playgroud)
.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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)