圣杯布局和双飞翼布局

圣杯布局

三栏布局是中间盒子优先渲染,两边的盒子宽度固定不变,即使页面宽度变小,也不影响我们的浏览。

  1. 左右栏固定,中间自适应。
  2. 优先渲染中间栏部分。
圣杯布局的实现

实现原理:

  1. 一个大的div包裹着三个小的div,分别对div设置class属性,container, center,left,right。

  2. center 设置宽度为100%,left宽度为100px,right设置为150px,分别给不同的背景颜色background-color,这个时候呈现的是三行布局;

  3. 给三个小的兄弟div设置左浮动float:left,大的父级div设置清除浮动overflow:hidden;这个时候center在一行沾满整个宽度,left和right并列在一行;

  4. 使用margin-left将左右盒子拉至左右两边,左边盒子:margin-left:-100%;右边盒子:margin-left:-150px;这个时候就是三列布局了;

  5. 但是有一个问题就是挡住了中间center里面的内容,这个时候的解决方式是给大的div父级元素设置padding,给左右栏留出位置,padding:0 150px 0 100px;

  6. 再之后给左右两栏弄到相应的位置,使用相对定位position:relative;左边栏left:-100px;右边栏right:-1500px;

  7. 以上是实现的原理,可是在浏览器缩小的一定的窄度时,会出现左右两栏被挤出到下一栏的效果;因为设置了相对定位,所以当发生重叠时,就会造成布局混乱,解决方式一:给父容器计算最小宽度calc(left盒子宽度*2+right盒子宽度);解决方式二:使用双飞翼布局。

效果图如下:(可不用设置头部的尾部)
在这里插入图片描述

html代码
<div class="container">
    <div class="center">
        center
    </div>
    <div class="left">
        left
    </div>
    <div class="right">
        right
    </div>
</div>
css代码
.container{
    background-color: #ccc;
    overflow:hidden;
    padding: 0 150px 0 100px;
    calc(100 * 2 + 150);
}
.center,.left,.right{
    min-height: 200px;
    float: left;
    position: relative;
}
.center{
    width: 100%;
    background-color: red;

}
.left{
    width: 100px;
    background-color: blue;
    margin-left: -100%;
    left: -100px;
}
.right{
    width: 150px;
    background-color: green;
    margin-left: -150px;
    right: -150px;
}

双飞翼布局

鉴于以上布局有些麻烦,可试试双飞翼布局,主要不同的是在中间部分的div再套上一层div,大的容器就不再需要设置padding值,左右栏盒子也不用再设置相对布局,代码精简了很多,而且不会出现上面变的特别窄布局会乱掉的问题。

html代码:

<div class="container">
    <div class="center">
        <div class="center-content">
        	center
        </div>
    </div>
    <div class="left">
    	left
    </div>
    <div class="right">
    	right
    </div>
</div>
css代码
.container{
	overflow: hidden;
}
.center,.left,.right{
    min-height: 200px;
    float: left;
}
.center{
    background-color: red;
    width: 100%;
    min-height: 220px;
}
.left{
    width: 100px;
    background-color: blue;
    margin-left: -100%;
}
.right{
    width: 150px;
    background-color: green;
    margin-left: -150px;
}
.center-content{
    background-color: yellow;
    margin: 0 150px 0 100px;
    height: 200px;
}

使用flex实现圣杯布局

相对以上两种,使用flex实现会更加使得代码简洁。
body代码片段
在这里插入图片描述 style代码片段
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值