两栏布局和三栏布局干货整理

一、两栏布局

1)浮动布局:边栏浮动,主栏留出相应的margin (边栏宽度)

<div id = "aside">
</div>
<div id = "main">
</div>
div{
  height:500px;
}
#aside{
  width:300px;
  background-color:yellow;
  float:left;
}
#main{
  background-color:aqua;
  margin-left:300px;
}

2)浮动布局+负外边距(双飞翼布局的两栏版)

<div id = "aside">
</div>
<div id = "main">
  <div id = "content"></div>
</div>
div{
  height:500px;
}
#aside{
  width:300px;
  background-color:yellow;
  float:left;
  margin-right:-100%;
}
#main{
  width:100%;
  float:left;
}
#content{
  margin-left:300px;
  background-color:aqua;
}

左侧固定栏指定一个右侧的100%的负外边距,为整个屏幕的宽度

使得main的最左侧可以与屏幕的最左侧对齐

此时的main的宽度为100%,因此需要为其子内容centent指定一个左侧的外边距,用于空出左侧栏的位置

3)绝对定位:左侧栏宽度固定并绝对定位在最左侧,右侧主栏设置一个margin-left为边栏的宽度

<div id = "aside">
</div>
<div id = "main">
</div>
#aside{
    position:absolute;
    left:0;
    width:200px;
}
#main{
    margin-left:200px;
}

4)flex布局(经典的固定-自适应布局)

<div id="container">
    <div id = "aside"></div>
    <div id = "main"></div>
</div>
#container{
    display:flex;
}
#aside{
    flex:0 0 200px;
}
#main{
    flex: 1 1;
}

二、三栏布局

1)绝对定位:左右侧栏分别用绝对定位固定在左侧和右侧,中间栏用margin-left和margin-right空出左右位置

<div id = "left">
</div>
<div id = "main">
</div>
<div id = "right">
</div>
html,body{
  margin:0;
  padding:0;
  height:100%;
}
div{
  height:100%;
}
#left{
  width:200px;
  background-color:yellow;
  position:absolute;
  top:0;
  left:0;
}
#main{
  background-color:aqua;
  margin-left:200px;
  margin-right:300px;
}
#right{
  width:300px;
  background-color:orange;
  position:absolute;
  top:0;
  right:0;
}

2)浮动定位法

另左侧栏和右侧栏向左和向右浮动,中间栏放在最后

再利用左右边距margin空出左右位置

3)浮动布局+负外边距布局(双飞翼布局)

  1. 三栏都采用左浮动
  2. 中间栏div写在最前面,宽度为100%
  3. 为左侧栏设置margin-left:-100%,也就是整个屏幕的100%,左侧栏就跑到中间栏的最左侧
  4. 右侧栏也是左浮动,利用margin-left:-300px;(右侧栏的宽度),使其到主栏的最右边
<!--中间栏写在最前面-->
<div id = "main">
  <div id="content"></div>
</div>
<div id = "left">
</div>

<div id = "right">
</div>
html,body{
  margin:0;
  padding:0;
  height:100%;
}
div{
  height:100%;
}


#main{
  background-color:aqua;
  width:100%;
  float:left;
}
#left{
  width:200px;
  background-color:yellow;
  float:left;
  margin-left:-100%;
}

#right{
  width:300px;
  background-color:orange;
  float:left;
  margin-left:-300px;
}

#content{
  margin-left:200px;
  margin-right:300px;
}

这里面的main其实是占据了整个屏幕的宽度,而centent设置了margin,所以内容不会被遮挡

4)圣杯布局

前面与双飞翼布局类似,先渲染中间弹性区,再通过给左右盒子设置负边距实现同一行的显示“固定-自适应-固定”布局

圣杯布局没有中间centent(相比于双飞翼)所以两边的盒子会覆盖掉中间的内容

So,Next,利用父级元素设置左右内边距padding-left和padding-right,把三个盒子往中间挤,边上留出盒子宽度的空白


再给左右两个盒子加一个定位

.left{ position: relative; left: -200px;}
.right{position: relative;right: -200px;}


圣杯布局和双飞翼布局的不同之处就在于,中间内容不被遮挡,的实现方式

一个是通过增加一个div,content

一个是通过给主元素设置内边距padding











猜你喜欢

转载自blog.csdn.net/weixin_37719279/article/details/81020091