三栏布局之圣杯布局

415 阅读2分钟

圣杯布局

前言: 圣杯布局双飞翼布局是前端面试时常问的问题,因为它既能体现你懂HTML结构又能体现出你对HTML+CSS布局的掌握。事实上,圣杯布局其实和双飞翼布局是一回事。它们实现的都是三栏布局,两边的盒子宽度固定,中间盒子自适应,也就是我们常说的固比固布局。它们实现的效果是一样的,差别在于其实现的方法。

首先我们来看一下效果图

Alt text

第一步:构建页面结构

<div id="header">头部</div>
<div id="container">
	<div id="center" class="column">主要内容</div>
	<div id="left" class="column">次要内容</div>
	<div id="right" class="column">侧边栏</div>
</div>
<div id="footer">页脚</div>

第二步:为各个容器添加背景和高度

	body{
	    min-width: 500px;
	    margin: 0;
	    padding: 0;
	    text-align: center;/*文本居中*/
	}
	#container .column{
	    height: 500px;
	}
	#center{
	    background: #cecece;
	}
	#left{
	    background: red;
	}
	#right{
	    background: orange;
	}
	#header,
	#footer {
	    background: gray;
	    height: 50px;
	}

第三步:为各个容器添加宽度和为container(主要内容)添加内边距

	body{
            min-width: 550px;
            margin: 0;
            padding: 0;
            text-align: center;/*文本居中*/
        }
        #container{
            padding-left: 300px;/*左内边距*/
            padding-right: 200px;/*右内边距*/
        }
        #container .column{
            height: 400px;
        }
        #center{
            background: #cecece;
            width: 100%;
        }
        #left{
            background: red;
            width: 300px;
        }
        #right{
            background: orange;
            width: 200px;
        }
        #header,
        #footer {
            background: gray;
            height: 50px;
        }

效果图如下

Alt text

第四步:让主要内容的三个容器浮动(脱离文档流),同时页脚(footer)因上面的容器浮动了,页脚会自动上移到头部(header)下方,所以利用clear属性为其清除浮动

	#container .column{
            height: 300px;
            float: left;
        }
        #footer{
            clear: both;
        }

效果图如下

Alt text

第五步:让次要内容(left)移到左边

首先为其容器添加相对定位

	#container .column{
            height: 300px;
            position: relative;/*相对定位*/
            float: left;
        }

其次,我们让次要内容(left)的外负边距设为-100%(因为主要内容的宽度为100%)

	#left{
            background: red;
            width: 300px;
            margin-left: -100%;
        }

效果图如下

Alt text

在利用在相对定位的情况下,右移动300px

	#left{
            background: red;
            width: 300px;
            margin-left: -100%;
            right: 300px;
        }

效果图如下

Alt text

第六步:同样的道理,让侧边栏(right)移到右边

	#right{
            background: orange;
            width: 200px;
            margin-right: -200px;
        }

最终效果图如下

Alt text

提醒:是不是已经get到技能了,接下来,你们可以利用浏览器的开发工具(F12)测试一下效果,看是不是,中间自适应,两旁固定宽度