是否可以动态设置一个div的宽度,然后将其高度设置为该宽度的某个百分比。就像这样:
#myDiv{
width:%100;
height: {35% of width};
}
我希望无论div的宽度是多少,都能保持其宽高比。
您可以通过CSS将高度设置为零,然后在padding-bottom中添加百分比来实现此操作。您可能需要微调一下以获得所需的结果,但这里有一个带有示例的演示:
http://jsfiddle.net/wbq8o3s7/#myDiv {
width: 100%;
height: 0;
padding-bottom: 35%;
background-color: #333;
}
<div id="myDiv"></div>
HTML:
<div class='box'>
<div class='content'>All your content are belong to us</div>
</div>
.box{
position: relative;
width: 50%; /* desired width */
}
.box:before{
content: "";
display: block;
padding-top: 100%; /*What you want the height to be in relation to the width*/
}
.content{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
完成了,太棒了...
来源:纯CSS
尝试一个简单的JavaScript:
document.getElementById("elemID").style.height =
Math.round((document.getElementById("elemID").style.width * 100) / 35) + "px";
这将获取宽度的百分比(四舍五入),并将其赋值给高度。