CSS的单列布局与二&三列布局

来源:互联网 发布:php的配置文件在哪里 编辑:程序博客网 时间:2024/05/22 04:26

这里介绍CSS常用的单列布局与二&三列布局,作为记录,希望自己的基本功能够更扎实。

单列布局

常见的单列布局有两种:

  • header,content和footer等宽的单列布局
  • header与footer等宽,content略窄的单列布局

对于前者:
通过对header,content,footer统一设置width(max-width)即可得到。

<div class="header"></div><div class="content"></div><div class="footer"></div>
.header{    margin:0 auto; //margin的作用是居中    max-width: 960px;    height:100px;    background-color: blue;}.content{    margin: 0 auto;    max-width: 960px;    height: 400px;    background-color: aquamarine;}.footer{    margin: 0 auto;    max-width: 960px;    height: 100px;    background-color: aqua;}

效果图:

这里写图片描述

对于后者:
需要将header和footer的宽度一起设置,然后将content和header/footer的内容(如导航栏)一起设置。

<div class="header">    <div class="nav"></div></div><div class="content"></div><div class="footer"></div>
.header{    margin:0 auto;    max-width: 960px;    height:100px;    background-color: blue;}.nav{    margin: 0 auto;    max-width: 800px;    background-color: darkgray;    height: 50px;}.content{    margin: 0 auto;    max-width: 800px;    height: 400px;    background-color: aquamarine;}.footer{    margin: 0 auto;    max-width: 960px;    height: 100px;    background-color: aqua;}

效果图:

这里写图片描述

二&三列布局

二列布局与三列布局的原理相同,将三列布局减少一个侧边栏即可得到二列布局。

利用float和margin得到三列布局

原理:将两个侧边栏分别向左向右浮动,通过设置中间的主栏的margin为它们留出空间,形成三列布局。

<!--注意最后写不浮动的main,不然浮动元素会到其下面 -->  <div class="left"></div>  <div class="right"></div>  <div class="main"></div>
.left{    float: left;    width: 200px;    height:400px;    background-color: blue;}.right{    float: right;    width: 200px;    height: 400px;    background-color: darkgray;}.main{    margin-left: 220px;    margin-right: 220px;    height: 400px;    background-color: aquamarine;}

效果图:

这里写图片描述

注意:只设置一个浮动即可得到两列布局。

利用position和margin进行三列布局

原理:通过将两个侧边栏的position设置为absolute,然后将左边栏的left设置为0,右边栏的right设置为0,主栏设置margin为边栏留出空间,即可得到三列布局。

 <div class="left"></div> <div class="right"></div> <div class="main"></div>
.left{    position: absolute;    left: 0;    width: 200px;    height:400px;    background-color: blue;}.right{    position: absolute;    right: 0;    width: 200px;    height: 400px;    background-color: darkgray;}.main{    margin-left: 220px;    margin-right: 220px;    height: 400px;    background-color: aquamarine;}

效果图:

这里写图片描述

同样,将定位元素改为一个可以得到两列布局。

还有几种常用的布局,如圣杯布局,双飞翼布局以及有效的flexbox,将在其它文章中记录。

原创粉丝点击