DIV水平居中和垂直居中布局
一、水平居中
1. inline-block + text-align
text-align(他会有继承) 作用在块级元素上,会让块级元素的inline-block子级 ,进行排列
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
width: 200px;
text-align: center;
}
.child{
display: inline-block;
}
2. table + margin
table如果不给它的所在元素设置宽的话,他的宽会是由内容撑开
<div class="parent">
<div class="child">demo</div>
</div>
.child{
display: table;
margin: 0 auto;
}
3.absolute + transform
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
position: relative;
}
.child{
position: absolute;
left:50%;
transform: translateX(-50%);
}
4.flex + justify content
flex的属性值其实也可以支持margin:0 auto;
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
display: flex;
justify-content: center;
}
或
.parent{
display: flex;
}
.child{
border: 1px solid green;
margin: 0 auto;
}
二、父元素和子元素都不定高,实现垂直居中
1.tale-cell + vertical-align
tale-cell 单元格这样的属性值,会自动让他的子元素居中
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
display: table-cell;
vertical-align: middle;
}
2.absolute + transform
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
position: relative;
}
.child{
position: absolute;
top:50%;
transform: translateY(-50%);
}
3.flex + align-items
align-items他的默认值是拉伸,布满整个容器
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
display: flex;
align-items: center;
}
三、容器大小不固定,同时居中
效果图.png
1.inline-block + text-align + tale-cell + vertical-align
tale-cell 单元格这样的属性值,会自动让他的子元素居中
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
text-align: center;
display: table-cell;
vertical-align: middle;
}
.child{
display: inline-block;
}
2.absolute + transform
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
position: relative;
}
.child{
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
3.flex + judifycontent + align-items
align-items他的默认值是 stretch拉伸,布满整个容器
<div class="parent">
<div class="child">demo</div>
</div>
.parent{
display: flex;
justify-content: center;
align-items: center;
}