面试题之居中问题
单行文本, inline 或 inline-block 元素
单行文本水平居中,使用text-aline:center
.box{
text-align:center
}
单行文本垂直居中,将行高设置为容器的高度
.box {
height:100px;
line-height:100px
}
结合上述两者可以实现单行文本水平垂直居中
.box {
height:100px;
line-height:100px;
text-align:center;
}
固定宽高块盒子水平垂直居中
一、absolute + 负 margin
父元素设置position为relation,子元素设置position为absolute,并将偏移量top和left都设置为父元素的50%,最后设置margin-top和margin-left分别设置为元素高度和宽度负的一半。
.pre {
position:relative;
width:200px;
height:200px
}
.child {
position:absolute;
top:50%;
left:50%;
width:100px;
height:100px;
margin:-50px 0 0 -50px
}
二、absolute + margin auto
父元素设置position为relation,子元素设置position为absolute。四个方向的偏移量都设置为0,margin设置为auto
.pre {
position:relative;
width:200px;
height:200px
}
.child {
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
width:100px;
height:100px;
margin:auto;
}
三、absolute + calc
calc是一个计算属性,可以用于样式的计算
top:calc(50% - 50px) 表示的是,距离顶部的距离为父元素的一半减去当前元素高度的一半50px。
.pre {
position:relative;
width:200px;
height:200px
}
.child {
position:absolute;
width:100px;
height:100px;
top:calc(50%-50px);
left:calc(50%-50px)
}
不固定宽高块级盒子水平垂直居中
一、absolute + transform
父元素position设置为reactive,子元素设置为absolute,偏移量top、left设置为50%,transform:transleate(-%50,-50%)
.pre {
position:relative;
width:200px;
height:200px
}
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
二、line-height + vertical-align
将父元素的行高设置为其容器的高度,这样可以实现垂直居中,在设置text-align为center,达成水平居中。然后将子元素设置为行内块元素,就可以达成水平垂直居中。
.pre {
width:200px;
height:200px;
line-height:200px;
text-align:center;
}
.box {
display: inline-block;
line-height: initial;
vertical-align: middle;
}
三、writing-mode
writing-mode是一种改变文字书写方向的手段,先设置父元素书写为垂直方向,并设置text-align实现垂直居中。然后改变子元素书写反向为水平方向并设置text-align来实现水平居中。前提还得设置子元素为行内块元素。
.pre {
width:200px;
height:200px;
writing-mode:vertical-lr;
text-align:center;
}
.box {
display: inline-block;
writing-mode:horizontal-tb;
text-align:center;
width:100%;
}
四、table-cell
.pre {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 200px;
}
.box {
display: inline-block;
}
五、flex
先将元素设置为弹性容器,然后设置align-items设置为center水平居中,justify-content为center垂直居中。
.pre {
display:flex;
align-items:center;
justify-content:center;
}
.box {
}
六、grid
将容器设置为网格布局,然后对元素本身的align-self和justify-self属性都设置为center
.pre {
display:grid;
width:200px;
height:200px;
}
.box {
align-self:center;
justify-self:cent
}