美文网首页
两边固定中间自适应

两边固定中间自适应

作者: 指尖轻敲 | 来源:发表于2018-06-20 17:48 被阅读0次

圣杯布局和双飞翼布局基本上是一致的,都是两边固定宽度,中间自适应的三栏布局,其中,中间栏放到文档流前面,保证先行渲染。解决方案大体相同,都是三栏全部float:left浮动,区别在于解决中间栏div的内容不被遮挡上,圣杯布局是中间栏在添加相对定位,并配合left和right属性,效果上表现为三栏是单独分开的(如果可以看到空隙的话),而双飞翼布局是在中间栏的div中嵌套一个div,内容写在嵌套的div里,然后对嵌套的div设置margin-left和margin-right,效果上表现为左右两栏在中间栏的上面,中间栏还是100%宽度,只不过中间栏的内容通过margin的值显示在中间。

1. 圣杯布局

外层设置左右内边距,里面三个元素全部左浮动,中间设置宽度为100%,左侧元素设置margin-left: -100%;就会向上移动一行。右侧元素同理。然后左右两个元素通过定位分别向左右移动。

<div class="container">
    <div class="center">中间元素</div>
    <div class="left">左边</div>
    <div class="right">右边</div>
</div>

.container{
    padding: 0 200px;
}
.right{
    background-color: yellow;
    width: 200px;
    height: 200px;
    float: left;
    margin-left: -200px;
    position: relative;
    right: -200px;
}
.center{
    background: blue;
    height: 150px;
    width: 100%;
    float: left;
}
.left{
    float: left;
    background:red;
    width: 200px;
    height: 200px;
    margin-left: -100%;
    position: relative;
    left: -200px;
}

2. 双飞翼

与圣杯布局前面都相同,但是在处理左右遮挡中间的问题上思路不同。给中间元素加了一个父元素。然后给这个父元素中的子元素设置margin.

<div class="center">
    <div class="inside">中间元素</div>
</div>
<div class="left">左边</div>
<div class="right">右边</div>

.right{
    background-color: yellow;
    width: 200px;
    height: 200px;
    margin-left: -200px;
    float: left;
}
.left{
    background-color: red;
    width: 200px;
    height: 200px;
    margin-left: -100%;
    float: left;
}
.center{
    background: blue;
    width: 100%;
    height: 150px;
    float: left;
}
.inside{
    margin: 0 200px;
}

3. flex布局

通过order设置各元素的位置,默认是0;左右固定宽度,中间设置flex:1,元素占父元素的比例(因为没有其他同级元素设置,所以自己占全部)。弹性布局就是这么吊。

body{
    display: flex;
}
.center{
    flex: 1;
}
.left{
    order: -1;
    width: 200px;
}
.right{
    width: 200px;
}

或者用flex-grow设置中间元素的放大比例,使其布满剩余所有空间。而且左右元素还可以通过flex-basis设置在分配剩余空间之前此项目的宽度。

.center{
    flex-grow: 1;
}
.left{
    order: -1;
    flex-basis: 200px;
}
.right{
    flex-basis: 200px;
}

4. 绝对定位布局

body{
    position: relative;
}
.center{
    margin: 0 200px;
}
.left{
    width: 200px;
    position: absolute;
    left: 0;
    top: 0;
}
.right{
    width: 200px;
    position: absolute;
    right: 0;
    top: 0;
}

相关文章

网友评论

      本文标题:两边固定中间自适应

      本文链接:https://www.haomeiwen.com/subject/vtfdeftx.html