[前端知识点]css三栏布局


前言

常见的三栏布局方式: float布局、Position定位、table布局、弹性(flex)布局、网格(grid)布局

设定高度100,左右宽度300,中间自适应
三栏布局
html模板如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三栏布局</title>
    <style type="text/css">
      *{
        margin: 0;
        padding: 0;
      }
    </style>
</head>

<body>
  <div class="main">
    <div class="left"></div>
    <div class="center"></div>
    <div class="right"></div>
  </div>
</body>
</html>

一、float布局

float最初的设计的初衷是为了解决文字环绕的问题 ,即给一个图片设置float属性之后会使文字环绕在图片周围显示。
float之所以可以实现文字环绕是源于设置float属性的元素可以脱离文档流,使父元素高度塌陷。

.left{
  float: left;
  width: 300px;
  height: 100px;
  background: #1d9f33;
}
.right{
  float: right;
  width: 300px;
  height: 100px;
  background: red;
}
.center{
  margin-left: 300px;
  margin-right: 300px;
  height: 100px;
  background-color: #4990E2;
}

为了不影响其他元素的显示,我们需要清除浮动,具体可见[前端知识点]css清除浮动

二、position布局

position 的属性有5种 :

inherit: 继承父元素的position属性值
static: 默认值,没有定位
fixed: 生成绝对定位的元素,相对于浏览器窗口进行定位(不管屏幕内容怎么滑动,其位置不会改变)
relative:生成相对定位,相对于其正常位置进行定位
absolute:生成绝对定位的元素,相当于static定位以外的第一个父元素进行定位。

给其父元素添加 position:relative属性, 这样这三个子元素可以相对于父元素进行绝对定位

.main{
  position:relative;
}
.left{
    position: absolute;
    left: 0;
    width: 300px;
    background-color: red;
}
.center{
    position: absolute;
    left: 300px;
    right: 300px;
    background-color: blue;
}
.right{
    position: absolute;
    right: 0;
    width: 300px;
    background-color: #3A2CAC;
}

三、table布局

table是一种常见的布局方式, 可以将整个页面按照表格的方式设置为多行多列
CSS中可以使用 display: table 的方式使用table布局, 同时设置子元素为列的属性为display:table-cell

.main{
  width: 100%;
  display: table;
}
.left,.center,.right{
  display: table-cell;
}
.left{
  width: 300px;
  background-color: red;
}
.center{
  background-color: blue;
}
.right{
  width: 300px;
  background-color: red;
}

四、flex布局

flex布局是W3C提出了一种新的方案,可以简便、完整、响应式地实现各种页面布局
当给元素设置display:flex,则该元素就是一个flex容器,其子元素就是容器成员,称之为flex项目,每个项目默认按照从左到右方式排列

.main {
    display: flex;
}
.left{
    width: 400px;
    background-color: red;
}
.center{
	flex:1;
    background-color: blue;
}
.right{
    background-color: red;
    width: 400px;
}

flex其他方式可参考flex教程

五、grid布局

grid将网页划分成一个又一个网格,可以任意组合不同的网格,做出各种各样的布局

将属性 display 值设为 grid 或 inline-grid 就创建了一个网格容器,所有容器直接子结点自动成为网格项目

gird提供了 gird-template-columns、grid-template-rows属性让我们设置行和列的高、宽

.main{
  display: grid;
  width: 100%;
  grid-template-rows: 100px;  /*设置行高*/
  grid-template-columns: 300px auto 300px;  /*设置三列数属性*/
}
.left{
  background: red;
}
.main{
  background: blue;
}
.right{
  background:red;
}

如果还有其他推荐布局,欢迎大家私信或评论区分享

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值