回答(9)
3 years ago
使用jQuery,您可以通过执行此操作来实现
var cw = $('.child').width();
$('.child').css({'height':cw+'px'});
查看http://jsfiddle.net/n6DAu/1/上的工作示例
3 years ago
[更新:虽然我独立发现了这个技巧,但我知道Thierry Koblentz打败了我 . 你可以在A List Apart上找到他的2009 article . 信用到期的信用 . ]
我知道这是一个老问题,但我遇到了类似的问题,我只用CSS解决了 . 这是我讨论解决方案的blog post . 帖子中包含的是live example . 代码转发如下 .
HTML:
some text
CSS:
#container {
display: inline-block;
position: relative;
width: 50%;
}
#dummy {
margin-top: 75%; /* 4:3 aspect ratio */
}
#element {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: silver /* show me! */
}
#container {
display: inline-block;
position: relative;
width: 50%;
}
#dummy {
margin-top: 75%;
/* 4:3 aspect ratio */
}
#element {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: silver/* show me! */
}
some text
3 years ago
有一种方法使用CSS!
如果根据父容器设置宽度,可以将高度设置为0,并将padding-bottom设置为将根据当前宽度计算的百分比:
.some_element {
position: relative;
width: 20%;
height: 0;
padding-bottom: 20%;
}
这适用于所有主流浏览器 .
JSFiddle:https://jsfiddle.net/ayb9nzj3/
3 years ago
没有任何Javascript可能:)
HTML:
CSS:
.box {
position: relative;
width: 50%; /* desired width */
}
.box:before {
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.content {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
padding-top: 50%;
}
.ratio1_2:before{
padding-top: 200%;
}
.ratio4_3:before{
padding-top: 75%;
}
.ratio16_9:before{
padding-top: 56.25%;
}
3 years ago
Simple and neet : 根据视口宽度使用 vw 单位作为响应高度/宽度 .
vw:视口宽度的1/100 . (来源MDN)
DEMO
HTML:
1:1宽高比的CSS:
div{
width:80vw;
height:80vw; /* same as width */
}
表根据所需的纵横比和元素宽度计算高度 .
aspect ratio | multiply width by
-----------------------------------
1:1 | 1
1:3 | 3
4:3 | 0.75
16:9 | 0.5625
这种技术允许您:
在不使用 position:absolute; 的情况下插入元素内的任何内容
没有不必要的HTML标记(只有一个元素)
使用vh单位根据视口的高度调整元素纵横比
3 years ago
非常简单的方法jsfiddle
HTML
some text
CSS
#container {
width: 50%; /* desired width */
}
#element {
height: 0;
padding-bottom: 100%;
}
3 years ago
扩展填充顶部/底部技术,可以使用伪元素来设置元素的高度 . 使用浮点和负边距从流和视图中删除伪元素 .
这允许您在不使用额外的div和/或CSS定位的情况下将内容放在框内 .
.fixed-ar::before {
content: "";
float: left;
width: 1px;
margin-left: -1px;
}
.fixed-ar::after {
content: "";
display: table;
clear: both;
}
/* proportions */
.fixed-ar-1-1::before {
padding-top: 100%;
}
.fixed-ar-4-3::before {
padding-top: 75%;
}
.fixed-ar-16-9::before {
padding-top: 56.25%;
}
/* demo */
.fixed-ar {
margin: 1em 0;
max-width: 400px;
background: #EEE url(https://lorempixel.com/800/450/food/5/) center no-repeat;
background-size: contain;
}
3 years ago
真的,这属于对Nathan 's answer, but I' m的评论不允许这样做......
即使装在盒子里的东西太多,我也希望保持宽高比 . 他的例子扩大了高度,改变了纵横比 . 我找到了补充
overflow: hidden;
overflow-x: auto;
overflow-y: auto;
3 years ago
宽度:80vmin;身高:80vmin;
CSS可以实现80%的最小视图,高度或宽度