1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 前端面试题--水平垂直居中的方法

前端面试题--水平垂直居中的方法

时间:2023-09-23 03:22:05

相关推荐

前端面试题--水平垂直居中的方法

1.弹性盒子

给父元素设置

display:flex;

justify-content:center;

align-items:center;

.father {width: 200px;height: 200px;background-color: pink;display: flex;justify-content: center;align-items: center;}.son {width: 50px;height: 50px;background-color: yellow;}

2.line-height

只对文本有效果,对定宽高的盒子没用。所以在文本水平垂直居中对的时候使用。

且只对单行文本有效,多行文本不可

line-height: 200px; //垂直text-align: center; //水平

3.通过绝对定位的方式 absolute+负margin

需要知道子元素的宽高

.father {width: 200px;height: 200px;background-color: pink;position: relative;}.son {width: 50px;height: 50px;background-color: yellow;position: absolute;top: 50%;left: 50%;margin: -25px 0 0 -25px;}

4.也是绝对定位 absolute+margin:auto;

需要将各方向的距离都设置为0;再设margin:auto;

.son {width: 50px;height: 50px;background-color: yellow;position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;}

5.绝对定位+过渡

不需要子元素固定宽高

css3新增的transform:translate(-50%, -50%)即可

.son {width: 50px;height: 50px;background-color: yellow;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%)}

6.table-cell实现水平垂直居中:table-cell middle center组合使用

直接给父元素设置

为了明显观察,我们可以给它设置宽高与边框

注意:需要水平垂直的元素不能是块级元素(不然text-align:center不生效)

.father {width: 200px;height: 200px;background-color: pink;border: 1px solid red;display: table-cell;vertical-align: middle;text-align: center;}

7.grid(网格布局)

给父元素设置display:grid

给子元素设:align-self:center; justify-self:center;

.father {width: 200px;height: 200px;background-color: pink;border: 1px solid red;display: grid;}.son {width: 50px;height: 50px;background-color: yellow;align-self: center;justify-self: center;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。