三栏布局(左侧和右侧宽度固定,中间自适应)

三栏布局(左侧和右侧宽度固定,中间自适应)的五种实现方式

参考:https://www.cnblogs.com/chengzp/p/layout.html

1.浮动布局 ( float )

注:排列方式必须为 left  center  right。

思路:

设置左侧盒子左浮动,右侧盒子右浮动;

中间盒子的 Dom 写在最后。

<div class="container">
 <div class="left"> left </div>
 <div class="right"> right </div>
 <div class="center"> center </div>
</div>
.left{
    width:200px;
    background:green;
    float:left;
}
.center{
    background:yellow;
}
.right{
    width:200px;
    background:blue;
    float:right;
}

2. 绝对定位布局 (absolute)

思路:

设置父元素 position:relative; 子元素position:absolute;

左侧盒子的 left:0; 右侧盒子的right:0;

中间盒子的left:左侧盒子的宽度,right:右侧盒子的宽度。

<div class="container">
 <div class="left"> left </div>
 <div class="center"> center </div>
 <div class="right"> right </div>
</div>
.container{
    position:relative;
}
.left{
    width:200px;
    background:green;
    position:absolute;
    left:0;
}
.center{
    background:yellow;
    position:absolute;
    left:200px;
    right:200px;
}
.right{
    width:200px;
    background:blue;
    position:absolute;
    right:0;
}

 3.弹性布局 (flex)

思路:

设置父元素 display:flex; 和 flex-decoration:row;

设置左侧和右侧的盒子 flex-basis:希望显示的宽度; (注意:该属性的优先级高于 width )

设置中间盒子的 flex-grow:1; (该属性定义元素的放大比例,默认为0,此时剩余空间都会被该元素占满)

注:

若左侧和右侧的盒子flex-grow:1;中间的盒子flex-grow:2;此时会将剩余空间分为4份,中间的盒子占两份,左右侧盒子各占一份。

flex-basis:在分配空间之前,它们会先占据 flex-basis属性值 的空间,剩下的才属于剩余空间,然后父容器再把剩余空间分配给设置了 flex-grow 的容器。

设置 flex 属性之后,子元素的 float , clear, vertical-align 属性会失效。

<div class="container">
 <div class="left"> left </div>
 <div class="center"> center </div>
 <div class="right"> right </div>
</div>
.container{
    display:flex;
    flex-direction:row;
    align-items:center;
}
.left{
    flex-basis:200px;
    width:200px;
    background:green;
}
.center{
    flex-grow:1;
    background:yellow;
}
.right{
    /* flex-basis 的优先级比 width 高 */
    flex-basis:100px;
    width:200px;
    background:blue;
}

4. 表格布局 ( table )

思路:

设置父元素 display:table; 和 width:100%;

设置所有子元素的  display:table-cell;

设置左侧盒子和右侧盒子 的宽度;

<div class="container">
 <div class="left"> left </div>
 <div class="center"> center </div>
 <div class="right"> right </div>
</div>
.container{
    display:table;
    width:100%;
}
.left{
    display:table-cell;
    width:200px;
    background:green;
}
.center{
    display:table-cell;
    background:yellow;
}
.right{
   display:table-cell;
    width:200px;
    background:blue;
}

5. 网格布局(grid ) 

思路:

设置父元素 display:grid;  grid-template-columns:左侧宽度  中间宽度 右侧宽度; grid-template-rows:行显示的高度; 

<div class="container">
 <div class="left"> left </div>
 <div class="center"> center </div>
 <div class="right"> right </div>
</div>
.container{
    display:grid;
    grid-template-columns: 200px auto 200px;
    grid-template-rows: 50px;
}
.left{
    background:green;
}
.center{
    background:yellow;
}
.right{
    background:blue;
}

猜你喜欢

转载自blog.csdn.net/Lyj1010/article/details/88621618