css 布局


单列布局

水平居中

  • 使用inline-block 和text-aline
1
2
3
4
5
6
7
.parent{text-align: center;}
.child{
width: 100px;
height:50px ;
background-color: aqua;
display: inline-block;
}
  • 使用margin:0 auto 来实现,必须指定宽度

  • 使用table实现,只需要对自身设置

1
2
3
4
5
.child{
background-color: aqua;
display: table;
margin: 0 auto;
}
  • 使用绝对定位实现,仅限ie9以上
1
2
3
4
5
6
7
.parent{position: relative}
.child{
position: absolute;
left: 50%;
transform: translate(-50%);
background-color: aqua;
}
  • 使用flex布局,兼容性差,不能大面积布局

    • 第一种

      .parent{
      display: flex;
      justify-content: center;
      }

    • 第二种

      .parent{

       display: flex;
      

      }
      .child{

       margin: 0 auto;
      

      }

垂直居中

  • 使用绝对定位
1
2
3
4
5
6
.parent{position:relative}
.child{
position:absolute;
top:50%;
transform:translate(0,-50%)
}
  • 用vertical-aline
1
2
3
4
5
6
7
8
9
10
11
.parent{
display:table-cell;
vertical-aline:middle;
height:20px;
}
//另一种方法
.parent{
display:inline-block;
vertical-aline:middle;
line-height:20px;
}
  • 使用flex实现
1
2
3
4
.parent{
display:flex;
align-items:center;
}

水平垂直全居中

  • 利用绝对定位实现
1
2
3
4
5
6
7
.parent{position:relative}
.child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
  • 利用flex实现
1
2
3
4
5
.parents{
display:flex;
justify-content:center;
align-items:center;
}
  • 利用vertical-aline,text-aline,inlne-block实现
1
2
3
4
5
6
7
8
.parent{
display:table-cell;
vertical-align:middle;
text-aline:center;
}
.child{
display:inline-block;
}

当内容不足一屏时footer紧贴底部

1.使用border-box
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<body>
...
<div class="footer"></div>
</body>

html{
height: 100%;
}
body{
min-height: 100%; /* 设置最小高度100% */
position: relative; /* 设置最小高度100% */
box-sizing: border-box; /* 设置盒模型为border-box,那样这个100%包括了下面的padding-bottom高度 */
padding-bottom: 120px; /* 高度为footer的高度 */
}
.footer{
position: absolute; /* 将footer绝对定位在底部 */
left: 0;
bottom: 0;
width: 100%;
height: 120px;
}

2.使用flex布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<body>
<div class="header"></div>
<div class="container"></div>
<div class="footer"></div>
</body>


html{
height: 100%;
}
body{
min-height: 100%;
display: flex; /* 设置flex */
flex-direction: column; /* 方向为垂直方向 */
}
.container{
flex: 1; /* 内容占满所有剩余空间 */
}

多列等高布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
.parent{
overflow: hidden;
resize: vertical;

}
.child1{
float: left;
width: 300px;
background-color: antiquewhite;
margin-bottom: -600px;
padding-bottom: 600px;
}
.child2{
float: left;
width: 300px;
background-color: aqua;
}
.child3{
float: left;
width: 300px;
background-color: antiquewhite;
margin-bottom: -600px;
padding-bottom: 600px;
}

Author: 杜宏飞
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source 杜宏飞 !
  TOC