父子div水平垂直居中不限于以下方式:
- 定位+transform
- before伪元素设置为innerblock,中对齐,text-align: center; vertical-align: middle;(基线有点迷)
- flex+auto
- flex
- 父级上下padding,子级margin:auto
- 父级flex定宽不定高,子级margin:xx%
html代码
<div class="wrapper">
<div class="content">
长城(The Great Wall),又称万里长城,是中国古代的军事防御工事,是一道高大、坚固而且连绵不断的长垣,用以限隔敌骑的行动。长城不是一道单纯孤立的城墙,而是以城墙为主体,同大量的城、障、亭、标相结合的防御体系。
</div>
</div>
定位+transform
.wrapper{
width:400px;
height:300px;
border:1px solid black;
position:relative;
}
.content{
width:300px;
position:absolute;
left: 50%;
top: 50%;
transform:translate(-50%, -50%);
background-color: #ccc;
}
flex+margin
.wrapper{
width:400px;
height:300px;
border:1px solid black;
display: flex;
}
.content{
width:300px;
margin:auto;
background-color: #ccc;
}
flex
.wrapper{
width:400px;
height:300px;
border:1px solid black;
display: flex;
align-items:center;
justify-content:center;
}
.content{
width:300px;
background-color: #ccc;
}
父级上下padding,子级margin:auto
父div的高度是子div的高度决定的
.wrapper{
width:400px;
padding: 50px 0;
border:1px solid black;
}
.content{
width:300px;
margin: auto;
background-color: #ccc;
}
父级flex定宽不定高,子级margin:xx%
相当于四个方向都被压缩了,但是字体大小是不变的,且父div的高度是子div的高度决定的
.wrapper{
width:400px;
border:1px solid black;
display:flex;
}
.content{
margin:10%;
background-color: #ccc;
}