基本HTML布局

4

我正在尝试实现一个简单的布局,类似于这样:

 _________________________
|     |   header    |     |
|  L  |_____________|  R  |
|     |             |     |
|     |             |     |
|     |             |     |
|     |    main     |     |
|     |             |     |
|     |             |     |
|     |             |     |
|_____|_____________|_____|

我已经开发出以下代码来完成我的目标:
<!DOCTYPE html>
<html>
<head>
    <title>Layout</title>
<style>

    * {
        margin: 0px;
        padding: 0px;
    }
    p {
        text-align: center;
    }
    div#left {
        float: left;    
        background-color: #777;
        width: 200px;
        height: 650px;
    }
    div#header {
        float: left;    
        background-color: #eee;
        width: 940px;
        height: 60px;
    }
    div#main {
        float: left;    
        width: 940px;
    }
    div#right {
        float: right;   
        background-color: #777;
        width: 200px;
        height: 650px;
    }
</style>
</head>

<body>
    <div id="left">
        <p>Left</p>
    </div>

    <div id="header">
        <p>Header</p>
    </div>

    <div id="main">
        <p>Main</p>     
    </div>

    <div id="right">
        <p>Right</p>
    </div>
</body>

但是我无法让“右”列与顶部保持对齐。有人可以指出我在CSS中需要更改什么来纠正这个问题吗? 谢谢!
3个回答

10

将右侧列移至 HTML 顶部:

<body>

    <div id="right">
        <p>Right</p>
    </div>

    <div id="left">
        <p>Left</p>
    </div>

    <div id="header">
        <p>Header</p>
    </div>

    <div id="main">
        <p>Main</p>     
    </div>
</body>

2

John Conde的答案是正确的。但是为了帮助您更好地理解,将您的宽度改为百分比,您就会明白他的意思。 :)

    <!DOCTYPE html>
    <html>
    <head>
       <title>Layout</title>
    <style>

      * {
       margin: 0;
       padding: 0;
      }
      p {
       text-align: center;
      }
      div#left {
       background-color: #777777;
       float: left;
       height: 650px;
       width: 15%;
      }
      div#header {
        background-color: #EEEEEE;
        float: left;
       height: 60px;
       width: 70%;
      }
      div#main {
       float: left;
       width: 70%;
      }
    div#right {
      background-color: #777777;
      float: right;
      height: 650px;
      width: 15%;
    }
    </style>
    </head>

    <body>
    <div id="left">
        <p>Left</p>
    </div>
    <div id="right">
        <p>Right</p>
    </div>
    <div id="header">
        <p>Header</p>
    </div>

    <div id="main">
        <p>Main</p>     
    </div>
    </body>

1
为了实现正确的、跨浏览器兼容的浮动布局,正确地排列元素非常重要。为了实现这一点,您应该始终让浮动元素出现在非浮动元素之前。
您还必须优先考虑垂直布局,例如,如果您的示例中的标题将横跨整个页面宽度,则此标题将出现在其后的任何浮动元素之前。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接