【问题标题】:Responsive div with fixed aspect ratio dynamic child div具有固定纵横比动态子 div 的响应式 div
【发布时间】:2019-01-26 15:14:33
【问题描述】:

Here 是一个 JSFiddle。我应用了适用于水平调整大小的padding trick。但是,它不适用于垂直调整大小。换句话说,我希望黄色 div 的高度为固定百分比,例如容器的 15%。但是黄色的纵横比应该保持不变。因此,如果我垂直调整大小(例如缩小),我的目标是减少黄色 div 的宽度以及高度,以便:1)保持纵横比。 2)保持黄色div的百分比宽度高度。如果没有 JavaScript,这可能吗?如果可用,我可以使用任何 CSS3。

下面也是代码:

html, body {
  height: 100%; 
} 
.container {
 position: relative;
  left: 10%;
  width: 80%;
  height: 80%;
  top: 10%;
  background-color: maroon;
}
.content {
  background-color: yellow;
    width: 20%;
    padding-top: 10%;
    bottom: 0;
    position: absolute;
    left: 40%;
    /* height: 15%; of course this doesn't work */
} 
<div class="container">
  <div class="content"> 
        
  </div>
</div>

编辑:Here 是使用 jQuery 的所需行为的小提琴。这是代码:

$(window).resize(function () {
    $(".content").height($(".container").height() / 5);
    $(".content").width($(".container").width() / 5);
    if ($(".content").width() / $(".content").height() < 3) {
        $(".content").height($(".content").width() / 3);
    }
    else {
        $(".content").width($(".content").height() * 3);
    }
    $(".content").css("left", ($(".container").width() - $(".content").width()) / 2);
}).resize();
html, body {
  height: 100%; 
} 
.container {
 position: relative;
  left: 10%;
  width: 80%;
  height: 80%;
  top: 10%;
  background-color: maroon;
}
.content {
  background-color: yellow;
    bottom: 0;
    position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="content"> 
        
  </div>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您可以使用媒体查询和视口尺寸。比如:

    // I used 15vw just as an example, you should do some maths and find the correct ratio/breakpoint
    // this makes the box react to the horizontal resize
    @media (min-width: 15vw) { 
      .content {
        height: 12vw;
        width: 28vw;
      }
    }
    
    // now, at that breakpoint, the box size depends on the viewport's height
    @media (max-height: 15vw) {
      .content {
        height: 80vh;
        width: 185vh;
      }
    }
    

    https://jsfiddle.net/f76p5nsr/

    就我个人而言,我会尝试将 vh 和 vw 用于这些块的所有尺寸,这也将帮助您进行数学计算。

    【讨论】:

    • 不幸的是,垂直调整大小仍然不起作用。我需要将黄色 div 的高度设置为容器高度的百分比。
    • @yazanpro,你试过我的小提琴吗?我可以看到黄色框调整大小,也许我不明白你需要什么
    • 黄色的高度应该是栗色高度的固定百分比,同时保持纵横比。
    • 在我的小提琴上,黄色框的高度等于该尺寸范围内的棕色容器的高度,如果您希望黄色框为 50%,只需将高度:80vh 更改为 40vh例如它的父母
    • 黄色上边缘和栗色上边缘之间的空间应始终为栗色高度的 80%。所以为了保持纵横比,黄色应该缩小以保持80%
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2018-05-24
    • 2015-11-20
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多