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

时间:2017-02-22 17:51:52

标签: javascript html css css3 flexbox

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

如果容器有GetFullHtmlFieldName,我希望广场的大小为height > width。如果容器有width x width,我希望广场的大小为width > height

当容器的尺寸发生变化时,儿童的尺寸应相应调整。

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

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

1 个答案:

答案 0 :(得分: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>