CSS学习知识点自检
之前面试的时候遇到过这题,当时脑袋空空,只想到了绝对定位 + translate位移这一种常用的方法,于是在这里进行方法总结。
让盒子水平垂直居中通常是相对于嵌套盒子而言的,是子盒子相对于父盒子的居中。
/* 嵌套盒子 */
<div class="father">
<div class="son"></div>
</div>
方法一:子绝父相 + 负margin
.father {
position: relative;
height: 200px;
width: 200px;
background-color: powderblue;
}
.son {
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
margin-top: -50px; /*子盒子往上走自身宽度的一半*/
margin-left: -50px; /*子盒子往左走自身宽度的一半*/
background-color: pink;
}
优点: 便于理解,兼容性好。
缺点: 需要知道选定盒子的宽高值。
方法二:子绝父相 + translate位移
.father {
position: relative;
height: 200px;
width: 200px;
background-color: powderblue;
}
.son {
position: absolute;
width:100px;
height: 100px;
top: 50%;
left: 50%;
transform: translate( -50%, -50%);
background-color: pink;
/*兼容*/
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
}
<--translate中的百分比单位是相对于本身元素而言的,不会影响到其他元素的位置-->
优点: 代码量少,便于理解,是对方法一的改良版;不需要考虑盒子的宽高值。
缺点: 需要考虑到浏览器兼容性问题。
方法三:子绝父相 + margin auto
.father {
position: relative;
height: 200px;
width: 200px;
background-color: powderblue;
}
.son {
position: absolute;
height: 100px;
width: 100px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background-color: pink;
}
优点: 兼容性也很好,不需要考虑盒子的宽高值
缺点: 代码量些许冗余。
方法四:弹性盒子Flex
.father {
height: 200px;
width: 200px;
background-color: powderblue;
display: flex;
/*控制元素在主轴(横轴)的对齐方式*/
justify-content: center;
/*设置元素在垂直方向上(纵轴)的对齐方式。*/
align-items: center;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
}
注意:此方法 让子盒子居中,但是样式要写在父元素上。
优点: 移动端使用方便,不需要考虑盒子的宽高值
缺点: pc端需要根据兼容情况来判定
在前三种子绝父相的方法中,若父元素不设置相对定位,则子元素是相对于浏览器屏幕的水平垂直居中。
待续。