仅限CSS的方法将div设置为90%宽度和3:1宽高比

epe*_*leg 2 css aspect-ratio

我有一个div,我想设置为其父容器宽度的90%,我希望设置它的高度,以达到特定的宽高比,比如说3:1.

.mydiv {
  width: 90%
  height: 30%(of-width);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点,不涉及JavaScript?

Ben*_*ull 6

在发布答案后很长时间内进行定制 - 您可以使用普通CSS设置元素的宽高比,而不使用任何宽高比的好看.它依赖于以百分比形式给出的填充从父元素的宽度开始测量,而不是像您期望的那样高度.我们可以利用这个,就像这样:

.aspect-box {
   width: 90%;
   height: 0;
   padding-top: 27%; /* because we want a ratio of 100:30 and the width 
                        is 90% of the parent width, We need the height to be
                        30% of this 90%, since we're referencing the parent
                        element's width, not this element. */
}
Run Code Online (Sandbox Code Playgroud)

因此,您将高度设置为0,将顶部填充设置为百分比,然后您将获得具有固定宽高比的框.问题是,你需要另外一点调整来把东西放进那个盒子里.将以前的代码更改为:

.aspect-box {
   position: relative;
   width: 90%;
   height: 0;
   padding-top: 27%; /* This is 90% of 30%, since we're referencing the parent element, not this element. */
}

.aspect-box .liner {
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
}
Run Code Online (Sandbox Code Playgroud)

放入<div class="liner">您的方面框,然后在其中放置您想要的任何内容.