将2个div并排对齐

时间:2012-02-19 15:51:46

标签: html css

我有一个问题是让2个div并排排列。根据我的理解,使用“float:left”应该这样做,但它不会 - div显示在彼此之上。我虽然它可能是浏览器,但我在FF,Opera和IE上试过它,结果是一样的。

这是我的代码

<head>
    <style>
        div.container{
            position: relative;
            width:800px;
            height: 1000px;
            background-color: red;
            overflow: hidden;
        }

        div.banner{
            position: relative;
            align:left;
            width: 800px;
            height: 100px;
            float:left;
            background-color: blue;
            clear:both;
        }
        div.navBar{
            position: absolute;
            width: 200px;
            height: 300px;
            float:left;
            background-color: yellow;
            clear: left;
        }

        div.content{
            position: absolute:
            width: auto;
            height: auto;
            float:left;
            background-color: orange;
            clear: right;
        }
    </style>
</head>

<body>
    <div name="banner" class="banner">
        This will be the banner
    </div>

    <div name="container" class="container">
        <div name="navBar" class="navBar">
            This will be the navbar
        </div>

        <div name="content" class="content">
            This will be the content
        </div>

    </div>
</body>

所有div都有不同的颜色,因此更容易看出会发生什么。

2 个答案:

答案 0 :(得分:2)

position:absolute是让它们重叠的原因。

删除绝对定位,它应该可以正常工作。

请参阅此处的操作:http://jsfiddle.net/5ULsG/

答案 1 :(得分:2)

这是一个完整的布局,包括你可能需要的页脚。绝对没有杂乱,是的。 :)

<div name="banner" class="banner">
This will be the banner
</div>

 <div name="container" class="container">
 <div name="navBar" class="navBar">
     This will be the navbar
 </div>

 <div name="content" class="content">
    This will be the content
  </div>
  <div name="footer" class="footer">
     Footer
  </div>

      div.container{
        width:800px;
        height: 1000px;
        background-color: red;
    }

    div.banner{
        width: 800px;
        height: 100px;
        background-color: blue;
    }
    div.navBar{
        float:left;
        width: 200px;
        height: 300px;
        background-color: yellow;
    }

    div.content{                      
        float:left;
        background-color: orange;
    }
    div.footer{                     
        clear:both;
        background-color: blueviolet;
    }

http://jsfiddle.net/L4Zjh/1/

相关问题