-
思路
内联元素居中布局:
水平居中:
行内元素可设置:text-align: center
flex布局设置父元素:display: flex; justify-content: center垂直居中:
单行文本父元素确认高度:height === line-height ,设置height, line-height
多行文本父元素确认高度:disaply: table-cell; vertical-align: middle块级元素居中布局
水平居中:
定宽: margin: 0 auto垂直居中:
position: absolute设置left、top、margin-left、margin-to(定高)
position: fixed设置margin: auto(定高)
display: table-cell
transform: translate(x, y)
flex(不定高,不定宽) -
css实现(其他样式代码自己补全)
<div id="app">
<div class="parent">
<div class="children"></div>
</div>
</div>
.parent{
width:200px;
height:200px;
}
.children{
width:50px;
height:50px;
background-color: rgb(255, 181, 25);
}
方法一:绝对定位 负magin值
//添加相对定位
.parent{
position: relative;
}
.children{
position: absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-25px;
}
方法二: 绝对定位 transform
.parent{
position: relative;
}
.children{
position: absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
方法三:定位 + left/right/bottom/top + margin
.parent{
position: relative;
}
.children{
position: absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
}
方法四:使用flex布局
.parent{
display:flex;
justify-content: center;
align-items: center;
}
方法五:table-cell布局
.parent{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.children{
display: inline-block;
}