如何使方形div适合父div

问题描述 投票:0回答:2

我有方形div,由padding-bottom: 100%;平方并为孩子设置position: absolute;。当父div的宽度大于高度时,出现方形溢出屏幕和滚动条。有没有办法使方形适合父div?

Update

很抱歉误导你。是的,我想把我的方框放到父div中。我为这个例子创建了新的jsfiddle

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

    @media all and (orientation: landscape) {
      div.stretchy-wrapper {
         width: 100vh;
         height: 100vh;
         padding-bottom: 0;
      }
    }

    div.stretchy-wrapper > div {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        color: black;
        font-size: 24px;
        text-align: center;
    }

    .outercontainer {
      background: red;
      width: 400px;
      height: 200px;
    }
<div class="outercontainer">
  <div class="stretchy-wrapper"></div>
</div>
css
2个回答
2
投票

如果在width模式下查看视口,请添加mediaquery以限制元素的heightlandscape

@media all and (orientation: landscape) {
  div.stretchy-wrapper {
     width: calc(100vh - 20px);
     height: calc(100vh - 20px);
     padding-bottom: 0;
  }
}

换句话说:如果视口的宽度是高度,为了确保1:1宽高比,你可以设置width等于100vh(减去一些填充,如果你需要)和height应该等于宽度。当这种情况发生时,不再需要padding-bottom

Jsfiddle fork


编辑完成后

由于你的outercontainer的高度是固定的,如果视口宽度是≥ 200px,那么设置一个固定的宽度和固定的高度都到200px。否则使用psuedoelement来保持1:1宽高比:

    div.stretchy-wrapper::before {
      display: block;
      content: "";
      padding-bottom: 100%;
    }

    @media all and (min-width: 200px) {
      div.stretchy-wrapper {
        width: 200px;
        height: 200px;
      }
      div.stretchy-wrapper::before {
         display: none;
      }
    }
    
    
    .outercontainer {
      max-width: 400px;
      height: 200px;
      border: 1px #9cb dashed;
    }
    
    .stretchy-wrapper {
      background: #9bc;
    }
<div class="outercontainer">
  <div class="stretchy-wrapper"></div>
</div>

最后结果

enter image description here


0
投票

实现此目的的一种方法是根据视口高度(vh单位,如answer provided by @fcalderan)设置div的宽度和高度,然后根据视口的高度设置max-width和max-height:

    div.stretchy-wrapper {
      position: relative;
      background: darkgreen;
      width: calc(100vh - 20px);
      height: calc(100vh - 20px);
      max-width: calc(100vw - 20px);
      max-height: calc(100vw - 20px);
    }

这样,无论视口如何变化,div都将保持正方形(但不需要mediaquery)。

© www.soinside.com 2019 - 2024. All rights reserved.