Open
Description
作为前端开发,CSS 常见布局应该是必须要掌握的,以前刚学 CSS,没什么概念,就只是重复地看一些知识点,现在把一些日常工作中常用到的布局结构,总结一下,也方便以后温故。
三栏布局
假设我们现在有如下 HTML 结构:
<div class="container">
<div class="left">这是左边</div>
<div class="middle">这是中间</div>
<div class="right">这是右边</div>
</div>
flex 实现
用 flex 实现三栏布局,是最直接易懂的,父级设置 display: flex,左右两个子元素设置 flex-basic 基础宽度,然后中间的设置 flex: 1 ,自适应。
.container {
display: flex;
}
.middle {
flex: 1;
height: 100px;
background-color: red;
}
.left {
flex: 0 1 200px;
height: 100px;
background-color: pink;
}
.right {
flex: 0 1 200px;
height: 100px;
background-color: blue;
}
float 实现
左边和右边的子元素分别浮动,中间的元素设置左右 margin,值为两个左右元素的宽度,注意,这种情况,DOM 的排列顺序必须是左边元素
-> 右边元素
-> 中间元素
.container {
overflow: hidden;
}
.left {
float: left;
width: 200px;
background-color: pink;
}
.right {
float: right;
width: 200px;
background-color: blue;
}
.middle {
margin-left: 200px;
margin-right: 200px;
background-color: red;
}
grid 实现
grid 布局比较简洁,直接使用 grid-template-columns
:
.container {
display: grid;
grid-template-columns: 200px auto 200px;
}
.left {
background-color: pink;
}
.right {
background-color: blue;
}
.middle {
background-color: red;
}
绝对定位实现
三个子元素全部都绝对定位,左边右边分别定位到端侧,中间使用 left,right 分别设置左右子元素的宽度,这种情况下元素全部脱离文档流了:
.container {
position: relative;
}
.left, .middle, .right {
position: absolute;
}
.left {
left: 0;
width: 200px;
background-color: pink;
}
.right {
right: 0;
width: 200px;
background-color: blue;
}
.middle {
left: 200px;
right: 200px;
background-color: red;
}
等分布局
用 CSS 实现:每三个元素排成一行,多余的元素自动换行排列。HTML 结构如下:
<div class="parent">
<div>子元素1</div>
<div>子元素2</div>
<div>子元素3</div>
<div>子元素4</div>
<div>子元素5</div>
<div>子元素6</div>
<div>子元素7</div>
</div>
CSS 实现:
.parent {
overflow: hidden;
background-color: red;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.parent div {
height: 50px;
margin: 5px 0;
flex: 1;
background-color: green;
width: calc((100% - 10px) / 3);
min-width: calc((100% - 10px) / 3);
max-width: calc((100% - 10px) / 3);
}