弹性布局和网格布局
1、Flex 弹性布局
1-1、Flex容器属性(常用)
flex-direction
justify-content
align-items
align-content
flex-wrap
flex-shrink
我们用上面的容器属性可以来实现一些常见的效果
1-1、水平排列;垂直排列
使用 flex-direction 控制排列方向
flex-direction: column; //垂直
flex-direction: row; //水平
<!-- HTML -->
<div class="box">
<div class="left">我是左边盒子</div>
<div class="right">我是右边盒子</div>
</div>
<!-- CSS -->
body {
margin: 0;
padding: 0;
}
.box {
width: 100%;
display: flex;
flex-direction: column; //垂直排列
//flex-direction: row; //水平排列
padding: 30px;
box-sizing: border-box;
}
.right,
.left {
height: 60px;
width: 100%;
border: 1px solid #f90;
}
1-2、垂直居中排列
display: flex;
justify-content: center;
align-items: center;
<!-- HTML -->
<div class="box">
<div class="left">我是左边盒子</div>
<div class="right">我是右边盒子</div>
</div>
<!-- CSS -->
body {
margin: 0;
padding: 0;
}
.box {
width: 100%;
display: flex;
flex-direction: column; //排列方向
padding: 30px;
box-sizing: border-box;
}
.right,
.left {
display: flex;
justify-content: center;
align-items: center;
height: 60px;
width: 100%;
border: 1px solid #f90;
}
2、Grid 网格布局
2-1、容器属性
grid-template-columns
grid-template-rows
grid-gap
justify-content
align-items
grid-column-start
grid-row-start
我们用上面的容器属性可以来实现一些常见的效果
2-2、九宫格的实现
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px ;
grid-gap: 15px;
容器指定了网格布局以后,接着就要划分行和列。grid-template-columns属性定义每一列的列宽,grid-template-rows属性定义每一行的行高。grid-gap用户设置行间距及列间距
<!-- HTML -->
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
</div>
/* CSS */
body {
margin: 0;
padding: 0;
}
.container{
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px ;
grid-gap: 15px;
}
.container > div{
background: #f90;
color: #fff;
font-size: 32px;
font-weight: bold;
}
2-3、卡片的展现形式
主要应用垂直网格线( grid-column-start )及水平网格线( grid-row-start)
grid-column-start: span 2;
grid-row-start: span 2;
span关键字,表示"跨越",即左右边框(上下边框)之间跨越多少个网格。
<!-- HTML -->
<div class="container">
<div id="item-1">1</div>
<div>2</div>
<div id="item-3">3</div>
<div>4</div>
<div>5</div>
</div>
/* CSS */
body {
margin: 0;
padding: 0;
}
.container{
display: grid;
grid-template-columns: 150px 150px 150px;
grid-template-rows: 80px 80px 80px ;
grid-gap: 1px;
}
.container > div{
background: #f90;
color: #fff;
font-size: 32px;
font-weight: bold;
}
#item-1{
grid-column-start: span 2;
grid-row-start: span 2;
}
#item-3{
grid-row-start: span 2;
}