有风的日子
首页  » 

资讯

 » 

教程精选

 » 

网页设计

 » 

查看资讯

使用CSS创建固定宽度的布局

发布时间: 2007-4-10 10:40    作者: 转载    来源: Builder.com.cn

21/212>

我最近的几篇专栏文章讨论了使用 XHTMLCSS 实现两列或三列页面布局的各个方面。到目前为止,所有例子都使用流式布局(也就是布局会自动扩展和适应浏览器窗口的宽度)。现在是时候考虑另外一种主要的页面布局方法了,这种布局方法是固定宽度布局。

很多 Web 构建人员倾向于使用固定宽度的布局进行页面设计,因为它们能生成精确且可预知的结果。这种方法与打印布局非常接近,对于设计人员和访问者来说都是一个很重要的舒适因素;另外,对于包含很多大图片和其它元素的内容,由于它们在流式布局中不能很好地表现,因此固定宽度布局也是处理这种内容的最好方法。

从 table 到 div

近年来,设计人员都使用表(table)来创建固定宽度的布局。表的列和行是对设计人员的布局表格(grid)的一种可行的模拟,所以一点也不奇怪设计人员为什么采用 HTML 表来完成页面布局。

然而,基于表的布局有一个明显的问题。除了语义上不适合用表来进行布局之外,产生的代码也很混乱,难于阅读,甚至难于维护——尤其是在包含合并的表单元格(cell)和嵌套表时。

使用 div 进行页面布局效果要好得多。除了这是推荐使用的最佳方法之外,代码的装载速度会更快,也更易于处理。

表及其单元格的格式(formatting)属性被借用到固定宽度布局中,因为指定这些元素的尺寸相当简单。其实通过 div 可以做到同样的事情,只要确定 div 精确的维数并使用绝对和相对定位将这些 div 定位到页面上即可。

一个固定宽度的例子

图 A 展示了一个典型的固定宽度的布局,该布局由顶部的一个标题,一个三列内容的区域(主内容列,每侧有一个工具条),和页面底部的一个页脚所组成。所有元素的宽度都是固定的;在浏览器窗口发布变化时它们的尺寸都不会变化。

下面的 XHTML 标记生成图 A 所示的页面。(出于简单考虑,内容被截短。)

<body>
<div id="head">
    <h1>header</h1>
</div>
<div id="columns">
    <div id="side1">
        <h3>side1</h3>
        <ul>
            <li>Let me not to the marriage of true minds</li>
            <li>Admit impediments; love is not love</li>
            <li>Which alters when it alteration finds</li>
            <li>Or bends with the remover to remove</li>
            <li>Oh, no, it is an ever fixed mark</li>
        </ul>
    </div>
    <div id="content">
        <h2>main content</h2>
        <p>That looks on tempests ... his height be taken.</p>
        <p>But bears it out ... alteration finds.</p>
        <p>Whose worth's unknown, ... the remover to remove.</p>
    </div>
    <div id="side2">
        <h3>side2</h3>
        <ul>
            <li>Let me not to the marriage of true minds</li>
            <li>Admit impediments; love is not love</li>
            <li>Which alters when it alteration finds</li>
        </ul>
    </div>
</div>
<div id="foot">
    <h3>footer</h3>
    <p>Or bends with ... height be taken. </p>
</div>
</body>

下面是将页面设计为固定宽度布局的 CSS 代码:

body {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
    margin: 0px;
    padding: 0px;
}
h2,h3 {
    margin-top: 0px;
    padding-top: 0px;
}
div#head {
    position: absolute;
    width:750px;
    height:100px;
    left:0px;
    top: 0px;
    background-color: #FFFF66;
}
div#columns {
    position: relative;
    width: 750px;
    top: 100px;
    background-color: #CCCCCC;
}
div#side1 {
    position:absolute;
    width:150px;
    top: 0px;
    left:0px;
    background-color: #FF6666;
}
div#content {
    position: relative;
    width: 450px;
    top: 0px;
    left: 150px;
    background-color: #999999;
}
div#side2 {
    position:absolute;
    width:150px;
    top: 0px;
    left: 600px;
    background-color: #00FF66;
}
div#foot {
    position: relative;
    width: 750px;
    clear: both;
    margin-top: 100px;
    background-color: #99FFFF;
}

21/212>

TAG

查看全部评论(0)

我来说两句

-5 -3 -1 - +1 +3 +5