zimo-article icon indicating copy to clipboard operation
zimo-article copied to clipboard

css 三栏布局【缺图】

Open laizimo opened this issue 6 years ago • 2 comments

前言

在网页中,我们常常会遇到布局这么一个概念。而对于一种相同的布局,可以使用不同的css来完成,这也是css有趣的地方。今天我们要讨论地布局就是最常见的三栏布局(也是面试中面试官喜欢问的话题)。

正文

其实,三栏布局可以有4种实现方式,每种实现方式都有各自的优缺点。

1.使用左右两栏使用float属性,中间栏使用margin属性进行撑开,注意的是html的结果

<div class="left">左栏</div>
<div class="right">右栏</div>
<div class="middle">中间栏</div>
.left{
  width: 200px;height: 300px; background: yellow; float: left;    
}
.right{
  width: 150px; height: 300px; background: green; float: right;
}
.middle{
  height: 300px; background: red; margin-left: 220px; margin-right: 160px;
}

first

缺点是:1. 当宽度小于左右两边宽度之和时,右侧栏会被挤下去;2. html的结构不正确

2. 使用position定位实现,即左右两栏使用position进行定位,中间栏使用margin进行定位

<div class="left">左栏</div>
<div class="middle">中间栏</div>
<div class="right">右栏</div>
.left{
    background: yellow;
    width: 200px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
}
.middle{
    height: 300px;
    margin: 0 220px;
    background: red;
}
.right{
    height: 300px;
    width: 200px;
    position: absolute;
    top: 0;
    right: 0;
    background: green;
}

image

好处是:html结构正常。

缺点时:当父元素有内外边距时,会导致中间栏的位置出现偏差

3. 使用float和BFC配合圣杯布局

将middle的宽度设置为100%,然后将其float设置为left,其中的main块设置margin属性,然后左边栏设置float为left,之后设置margin为-100%,右栏也设置为float:left,之后margin-left为自身大小。

<div class="wrapper">
    <div class="middle">
        <div class="main">中间</div>
    </div>
    <div class="left">
        左栏
    </div>
    <div class="right">
        右栏
    </div>
</div>
.wrapper{
    overflow: hidden;  //清除浮动
}
.middle{
    width: 100%;
    float: left;
}
.middle .main{
    margin: 0 220px;
    background: red;
}
.left{
    width: 200px;
    height: 300px;
    float: left;
    background: green;
    margin-left: -100%;
}
.right{
    width: 200px;
    height: 300px;
    float: left;
    background: yellow;
    margin-left: -200px;
}

bf-layout

缺点是:1. 结构不正确 2. 多了一层标签

4. flex布局

<div class="wrapper">
    <div class="left">左栏</div>
    <div class="middle">中间</div>
    <div class="right">右栏</div>
</div>
.wrapper{
    display: flex;
}
.left{
    width: 200px;
    height: 300px;
    background: green;
}
.middle{
    width: 100%;
    background: red;
    marign: 0 20px;
}
.right{
    width: 200px;
    height: 3000px;
    background: yellow;
}

first

除了兼容性,一般没有太大的缺陷

总结

一般现在使用较多的都是flex布局,这种布局是真的好用,哈哈

laizimo avatar Aug 24 '17 12:08 laizimo

最后边.right中的hight是不是误写了一个0。。。。

mhkz avatar Oct 11 '17 01:10 mhkz

赞。 PS:zhognjian 看着真难受。

HeathHsia avatar May 29 '18 09:05 HeathHsia