Html 响应高度与宽度成正比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11535827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:43:39  来源:igfitidea点击:

Responsive height proportional to width

htmlcssresponsive-design

提问by fedor.belov

Is it possible to implement the following logic usic HTML and CSS?

是否可以使用 HTML 和 CSS 实现以下逻辑?

width: 100%;
height: 30% of width;

What I want to implement: If I decrease the width, the height will also decrease proportionally.

我想实现的:如果我减小宽度,高度也会成比例地减小。

回答by Matt Coughlin

Padding %

填充%

This can be achieved by giving the element height:0and padding-bottom:30%.

这可以通过给元素height:0和来实现padding-bottom:30%

In all browsers, when padding is specified in %, it's calculated relative to the parent element's width. This can be a very useful feature for Responsive Design.

在所有浏览器中,当以 % 指定填充时,它是相对于父元素的宽度计算的。这对于响应式设计来说可能是一个非常有用的功能。

JSFiddle Demo

JSFiddle 演示

In the demo, the blue box at the top of the page is a single div. The height is responsive, and it can contain a variable amount of inline content without increasing the height. It tested fine in IE7/8/9/10, Firefox, Chrome, Safari, and Opera.

演示中,页面顶部的蓝色框是一个div. 高度是响应式的,它可以在不增加高度的情况下包含可变数量的内联内容。它在 IE7/8/9/10、Firefox、Chrome、Safari 和 Opera 中测试良好。

.content {
    width: 100%;
    height: 0;
    padding-bottom: 30%;
}
...
<div class="content"></div>

Padding % and absolute position

填充百分比和绝对位置

If there are any problems with using a 0-height element, the demoalso has a green box that's implemented using a wrapper element and absolute position. Not sure if there are any advantages to this approach.

如果使用 0-height 元素有任何问题,演示中还有一个使用包装元素和绝对位置实现的绿色框。不确定这种方法是否有任何优势。

.wrapper {
    position: relative;
    width: 100%;
    padding-bottom: 30%;
}
.wrapper .content {
    position: absolute;
    width: 100%;
    height: 100%;
}
...
<div class="wrapper">
    <div class="content"></div>
</div>

回答by ndp

This is now possible on modern browsers with vwand vhunits:

这现在可以在带有vwvh单位的现代浏览器上实现:

width: 100vw;
height: 30vw; /* 30% of width */

Browser support: http://caniuse.com/#feat=viewport-units

浏览器支持:http: //caniuse.com/#feat=viewport-units

Yeah!

是的!

回答by sebnukem

Also with JQuery, you could do:

同样使用 JQuery,您可以执行以下操作:

$(window).ready(function () {
    var ratio = 3 / 10, $div = $('#my_proportional_div');
    $div.height($div.width() * ratio);
    $(window).bind('resize', function() { $div.height($div.width() * ratio); });
});

because the Padding %solution suggested doesn't work with max/min-widthand max-min height.

因为建议的Padding %解决方案不适用于max/min-widthand max-min height