题目:假设高度已知,请写出三栏布局,左右两栏宽度各为300px,中间自适应,经典页面布局题目,共有五种比较流行的解决方案。
实现方式:
1. float布局
- 局限性:脱离文档流,需要清除浮动
- 优点:兼容性比较好
2. 绝对定位
- 局限性:脱离文档流,可用性差
- 优点:快捷
3. flex布局
- 优点:相对来说是最优的一种布局,随着浏览器支持越来越多
4. table布局
-
局限性:整个table是一个整体,在高度不确定时不适合使用
-
优点:兼容性好(ie8等)
5. grid网格布局
- 局限性:浏览器支持率低
注意:当高度不确定时,只有flex和table布局可以使用,其他布局会出现问题
第一种:Float布局
<!-- float布局解决方案 -->
<style>
.layout-float>div{
height: 100px;
}
.left{
background: red;
width: 300px;
float: left;
}
.right{
background: green;
width: 300px;
float: right;
}
.center{
background: blue;
}
</style>
</head>
<body>
<section class="layout-float">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div> <!-- 放在最后 -->
</section>
</body>
注意:这种float的三栏布局,需要将中间的div放在最后。
第二种:定位布局
<!-- 定位布局解决方案 -->
<style>
.layout-position>div{
height: 100px;
position: absolute;
}
.left{
left: 0;
background: red;
width: 300px;
}
.center{
left: 300px;
right: 300px;
background: blue;
}
.right{
right: 0;
background: green;
width: 300px;
}
</style>
</head>
<body>
<section class="layout-position">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</section>
</body>
第三种:Flex布局
<!-- flex布局解决方案 -->
<style>
.layout-flex{
display: flex;
}
.flex>div{
height: 100px;
}
.left{
background: red;
width: 300px;
}
.center{
flex: 1; /* 自适应,填满剩下的宽度 */
background: blue;
}
.right{
background: green;
width: 300px;
}
</style>
</head>
<body>
<section class="layout-flex">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</section>
</body>
第四种:Table布局
<!-- table布局解决方案 -->
<style>
.layout-table{
display: table;
width: 100%;
height: 100px;
}
.layout-table>div{
display: table-cell;
}
.left{
background: red;
width: 300px;
}
.center{
background: blue;
}
.right{
background: green;
width: 300px;
}
</style>
</head>
<body>
<section class="layout-table">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</section>
</body>
第五种:网格布局
<!-- 网格布局解决方案 -->
<style>
.layout-grid{
display: grid;
width: 100%;
grid-template-rows: 100px; /* 行高 */
grid-template-columns: 300px auto 300px; /* 3列 */
}
.left{
background: red;
}
.center{
background: blue;
}
.right{
background: green;
}
</style>
</head>
<body>
<section class="layout-grid">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</section>
</body>