多个垂直div,高度相对于宽度

时间:2013-02-03 10:12:02

标签: css html

我的css布局的一部分设置相对于宽度的div高度,以便所有屏幕尺寸的宽高比相同。这种方式我从来没有专门将div的高度设置为px值 - 高度只是宽度的纵横比。如果您之前没有遇到过这种技术,here is a good explanation

解决我的具体问题......

考虑到这一点,我创建了以下简单的div,它的宽度是它的两倍:(to see it in action please see this fiddle)

<html>
    <head>
       <style type="text/css">
.container
{
    position:relative;
    width:50%;/*half the width of the whole page*/
    margin:auto;/*center the whole thing*/
}
.relative_container
{
    background-color:blue;
    position:absolute;
    width:100%;
    top:0;
    left:0;
}
.set_height
{
    width:100%;
    height:100%;
    margin-top:50%;/*aspect ratio 2:1*/
}
       </style>
    </head>
    <body>
        <div class='container'>
            <div class='relative_container'>
                <div class='set_height'></div>
            </div>
        </div>
    </body>
</html>
到目前为止一切都很好。然而,我想在第一个下添加另一个相同的div。正如你在this fiddle中看到的那样,我不能让它们以任何方式显示在彼此之上。毫无疑问,答案在于清除div as demonstrated here,但我无法弄明白。

2 个答案:

答案 0 :(得分:2)

你的relative_container类是绝对定位的,所以它将两个div放在顶部:0,left:0具有相同的宽度和高度(所以它们在彼此的顶部)。这对你正在做的事情没有意义。

如果您将定位更改为亲戚,并将float: left添加到您的奇怪名称relative_container,您将获得所需的行为,因为它们将“浮动”到其父div中最左侧的位置。

此外,你的“清晰”div没有做任何事情。 clear属性告诉其他div不要浮动到给定div的右侧/左侧。如果div的宽度是100%(即它填满了父级),那么无论如何都没有任何东西可以漂浮在它旁边。

示例1:http://jsfiddle.net/NKRPe/13/

编辑: This second example在不使用虚拟div的情况下完成相同的任务。请注意,可以使用padding-toppadding-bottom

答案 1 :(得分:1)

添加到.container:

padding:25% 0 0;
相关问题