根据宽度设置div高度

时间:2015-01-09 02:15:01

标签: html html5 css3

是否可以动态设置divs宽度,然后将其高度设置为该宽度的某个百分比。像这样:

#myDiv{
    width:%100;
    height: {35% of width};
}

我想保留div的宽高比,无论宽度是多少。

3 个答案:

答案 0 :(得分:2)

您可以通过将高度设置为零然后在padding-bottom中添加百分比来使用CSS执行此操作。您可能需要稍微调整一下才能获得理想的结果,但这里只是一个例子 http://jsfiddle.net/wbq8o3s7/

#myDiv{
    width:%100;
    height:0;
    padding-bottom:35%;
    background-color:#333;
}

答案 1 :(得分:0)

尝试使用简单的JavaScript:

document.getElementById("elemID").style.height = 
Math.round((document.getElementById("elemID").style.width * 100) / 35) + "px";

这将获得with的百分比(圆角),并将其指定为高度。

答案 2 :(得分:0)

<强> HTML:

<div class='box'> 
    <div class='content'>All your content are belong to us</div> 
</div>

我们使用两个块元素来实现所需的行为,宽度为box,高度为内容。

CSS:

.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;
}
田田你完成了......

消息来源:Pure CSS

相关问题