【校招VIP】面试题准备:使盒子水平垂直居中的五种方法

08月24日 收藏 0 评论 0 前端开发

【校招VIP】面试题准备:使盒子水平垂直居中的五种方法

转载声明:文章声明:https://blog.csdn.net/weixin_46587293/article/details/123226295

HTML 结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<style>
  .wrapper {
    width: 500px;
    height: 300px;
    border: 2px solid #088;
    border-radius: 15px;
  }
  .content {
    width: 100px;
    height: 100px;
    background-color: #f88;
 
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
 
 
<div class="wrapper">
  <div class="content">我要居中</div>
</div>

1. 使用 flex 实现

把父元素设置为 flex 或者 inline-flex,使其中的盒子沿主轴和交叉轴水平垂直居中

1
2
3
4
5
6
/* 给 wrapper 添加下类 */
.flex-style {
    display: flex;
    justify-content: center;
    align-items: center;
}

2. 使用 position + margin 负边距实现

适用于已知内部盒子宽高

给父元素设置相对定位,给子元素设置绝对定位

再让子元素沿上方和左方偏移 50% 的父元素高宽,但因为是根据左上角偏移的

所以要用负边距 margin 来修正,修正的大小为宽高的一半

1
2
3
4
5
6
7
8
9
10
11
/* 给 wrapper 添加下类 */
.position-style {
    position: relative;
}
/* 给 content 添加下类 */
.position-sub {
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -50px 0 0 -50px;
}

3. 使用 position + transform 实现

适用于未知内部盒子宽高,已知亦可以

将上一个实现的 margin 改为 transform 即可

1
2
3
4
5
6
7
8
9
10
11
/* 给 wrapper 添加下类 */
.position-style {
    position: relative;
}
/* 给 content 添加下类 */
.position-sub {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

4. 使用 position + margin 填充实现

在子绝父相的基础上

使子元素上下作用的偏移均为 0

再让子元素自适应外边距 margin

注意:如果子元素的宽高是未设置的,则会填满整个父元素

1
2
3
4
5
6
7
8
9
10
11
12
13
/* 给 wrapper 添加下类 */
.position-style {
    position: relative;
}
/* 给 content 添加下类 */
.position-sub {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

5. 使用table-cell 实现

使用 table-cell,使父元素变为一个表格单元格,再用

vertical-align: middle;

text-align: center;

可使文字居中

这就要求中间的子元素需要有行级属性 inline 或 inline-

1
2
3
4
5
6
7
8
9
10
/* 给 wrapper 添加下类 */
.table-style {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
/* 给 content 添加下类 */
.table-sub {
    display: inline-flex;
}

总结

介绍了 div 盒子居中的五种方法,其中需要设置子元素宽高的有 第二种 定位 + 负边距 第四种 定位 + 外边距自适应

C 0条回复 评论

帖子还没人回复快来抢沙发