目录:
一,水平布局
二,垂直布局
三,两列布局
四,三列布局
五,多列布局
六,等高布局
一,水平布局
1,text-align
.parent{
text-align: center;
}
.child{
display: inline-block;
}
2,margin
.child{
width: 200px;
margin: 0 auto;
}
3,position
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
width: 200px;
margin-left: -100px;
}
4,table
.child{
display: table;
margin: 0 auto;
}
5,flex
1)justify-content
.parent{
display: flex;
justify-content: center;
}
2)margin
.parent{
display: flex;
}
.child{
margin: 0 auto;
}
二,垂直布局
1,vertical-align
#demo{
height:200px;
background-color: green;
}
#demo:after{
display:inline-block;
width:0;
height:100%;
vertical-align:middle;
content:'';
}
#demo p{
display:inline-block;
width: 200px;
vertical-align:middle;
}
2,table
#demo{
display: table;
height:200px;
background-color: green;
}
#demo p{
display:table-cell;
width: 200px;
vertical-align:middle;
}
3,transform
#demo {
position: relative;
height: 200px;
}
#demo p {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
4,position
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
height: 200px;
margin-top: -100px;
}
4,flex
1),align-items
.parent{
display: flex;
align-items: center;
}
2),margin
.parent{
display: flex;
}
.child{
margin: auto 0;
}
三,两列布局
1,左侧固定宽度,右侧自适应
.parent::after{
content: '';
clear: both;
display: table;
}
.left{
float: left;
width: 200px;
}
.main{
margin-left: 200px;
}
.parent {
display: table;
table-layout: fixed;
width: 100%;
}
.left {
width: 100px;
}
.left,
.main {
display: table-cell;
}
2,左侧自适应,右侧自适应
.parent::after{
content: '';
clear: both;
display: table;
}
.left{
float: left;
}
.main{
overflow:hidden;
}
四,三列布局
两侧固定宽度,中间自适应
1,float+margin
<style>
.parent::after{
content: '';
clear: both;
display: table;
}
.left{
float: left;
width: 200px;
}
.center{
margin:0 200px;
}
.right{
float: right;
width: 200px;
}
</style>
</head>
<body>
<div class="parent">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
2,position+margin
<style>
.left {
position: absolute;
top: 0;
left: 0;
width: 200px;
}
.right {
position: absolute;
top: 0;
right: 0;
width: 200px;
}
.center {
margin: 0 210px;
}
</style>
<body>
<div class="left">左</div>
<div class="center">中</div>
<div class="right">右</div>
</body>
五,多列布局
1,负margin
.parent {
margin-left: -20px
}
/*假设列之间的间距为20px*/
.column {
float: left;
width: 25%;
padding-left: 20px;
box-sizing: border-box;
}
2,flex
.parent {
display: flex;
}
.column {
flex: 1;
}
.column+.column {
margin-left: 20px;
}
六,等高布局
1,table
.parent {
display: table;
table-layout: fixed;
width: 100%;
}
.column {
display: table-cell;
background-color: #ccc;
}
2,margin,padding
.parent {
margin: 0 auto;
overflow: hidden;
}
.left {
float: left;
width: 100px;
background-color: #000;
margin-bottom: -1000px;
padding-bottom: 1000px;
}
.right{
float: left;
width: 400px;
background-color: green;
margin-bottom: -1000px;
padding-bottom: 1000px;
}
.clear{
clear: both;
}