居中方式
1、行元素居中
/*需在父级设置样式*/
.parent{
text-align: center;
height: 100px;
line-height: 100px;
}
2、通过absolute与margin:auto;居中
.child{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
3、通过absolute绝对定位居中
/*需在子辈设置样式,并且知道元素尺寸*/
.child{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px; /*高度的一半*/
margin-left: -50px; /*宽度的一半*/
}
/*未知元素尺寸*/
.child{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
/*translate()相对于元素本身尺寸偏移*/
}
4、通过flex布局居中
/*父级元素设置为flex弹性布局,并且父级需要设置高度*/
.parent{
height: 500px;
display: flex;
justify-content: center; /*水平方向居中*/
align-items: center; /*垂直方向居中*/
}
css样式百分比总结
相对于父元素宽高:[max/min-]width、left、right、padding、margin、[max/min-]height、top、bottom 等;
相对于自身宽高:border-radius、background-size、transform:translate()、transform-origin、zoom、clip-path 等;
相对于继承字号的:font-size 等;
相对于自身字号的:line-height 等;