水平居中
1.行内元素
为父元素设置text-align:center
<div class="outer">
<span>行内水平居中</span>
</div>
.outer{
text-align: center
}
2.定宽块元素
定义元素左右margin为auto
<div class="outer">
<div class="inner">定宽块级元素水平居中</div>
</div>
.outer{
width: 300px;
height: 300px;
background: teal;
}
.inner{
width: 200px;
height: 200px;
background: tan;
margin: 0 auto;
text-align: center
}
3.不定宽块级元素
①:设置块级元素样式display:inline
,然后再为父元素添加text-align:center
样式
<div class="outer">
<div class="inner">设置inline实现水平居中</div>
</div>
.outer{
width: 200px;
height: 200px;
background: teal;
text-align: center;
}
.inner{
background: tan;
display: inline;
}
②:position:relative;left:-50%
<div class="outer">
<div class="wrapper">
<div class="inner">设置relative实现水平居中</div>
</div>
</div>
.outer{
width: 200px;
height: 200px;
background: darkkhaki
}
.wrapper{
float: left;
width: 100px;
height: 100px;
position: relative;
left: 50%;
}
.inner{
height: 100px;
position: relative;
left: -50%;
background: tan;
}
垂直居中
1.table-cell布局
因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block,才能实现水平居中
<div class="outer">
<div class="content">
<div class="inner">table-cell实现垂直居中</div>
</div>
</div>
.outer{
width: 200px;
height: 200px;
background: darkkhaki;
display: table;
}
.content{
display: table-cell;
vertical-align: middle;
text-align: center;
background: red;
text-align: center
}
.inner{
display: inline-block;
width: 100px;
height: 100px;
background: tan
}
2.position
<div class="outer">
<div class="content">
<div class="inner">position实现垂直居中</div>
</div>
</div>
.outer{
width: 200px;
height: 200px;
background: darkkhaki;
}
.content{
float: left;
position: relative;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
background: red;
text-align: center
}
.inner{
position: absolute;
width: 100%;
height: 100%;
top: -50%;
left: -50%;
background: tan
}
3.flex
<div class="outer">
<div class="inner"></div>
</div>
.outer{
width: 200px;
height: 200px;
background: darkkhaki;
display: flex;
/*flex 盒子布局水平居中*/
justify-content: center;
/*flex 盒子布局垂直居中*/
align-items: center;
}
.inner{
width: 20%;
height: 20%;
background: tan
}