(自用面试题)水平垂直居中如何实现?

128 阅读1分钟

考频:
高频。

面试技巧:
面试时先答flex布局和grid网格布局即可,面试官追问再回答其他的。

背景:
在开发中经常遇到这个问题,即让子元素的内容在水平和垂直方向上都居中,内容不仅限于文字,可能是图片或其他元素。
实现居中的方法存在很多,可以将这些方法分成两个大类:

  • 子元素的宽高已知:2。
  • 子元素的宽高未知:1、3、4、5。
  1. 绝对定位 + margin: auto
    父元素设置为相对定位;子元素设置为绝对定位并且四个定位属性的值都设置为0,再将margin设置为auto。
<style>
    .father{
        position: relative;
        width: 250px;
        height: 250px;
        background-color: black;
    }
    .son{
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        width: 100px;
        height: 100px;
        margin: auto;
        background-color: yellow;
    }
</style>

<div class="father">
    <div class="son"></div>
</div>

这种方法子元素需要有宽高,没有宽高子元素会撑满整个父元素。

  1. 绝对定位 + margin: 负值
    父元素设置为相对定位;子元素设置为绝对定位并且top、left的值设置为50%,再将margin-left、margin-top分别设置为子元素宽高的一半的负值。该方法需要知道子元素自身的宽高
<style>
    .father {
        position: relative;
        width: 250px;
        height: 250px;
        background-color: black;
    }
    .son {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        margin-top:-50px;
        margin-left:-50px;
        background-color: yellow;
    }
</style>

<div class="father">
    <div class="son"></div>
</div>

这种方法子元素需要有宽高。

  1. 绝对定位 + transform
    父元素设置为相对定位;子元素设置为绝对定位并且top、left的值设置为50%,再将translate设置为-50%。
<style>
    .father {
        position: relative;
        width: 250px;
        height: 250px;
        background-color: black;
    }
    .son {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        background-color: yellow;
        transform: translate(-50%,-50%);
    }
</style>

<div class="father">
    <div class="son"></div>
</div>

这种方法子元素没有宽高也可。

  1. flex布局
    容器display设置为flex,justify-content和align-items设置为center。
<style>
    .father {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 250px;
        height: 250px;
        background-color: black;
    }
    .son {
        width: 100px;
        height: 100px;
        background-color: yellow;
    }
</style>

<div class="father">
    <div class="son"></div>
</div>

这种方法子元素没有宽高也可。

  1. grid网格布局
    容器display设置为grid,place-items设置为center。
<style>
    .father {
        display: grid;
        place-items: center;
        width: 250px;
        height: 250px;
        background-color: black;
    }
    .son {
        width: 100px;
        height: 100px;
        background-color: yellow;
    }
</style>

<div class="father">
    <div class="son"></div>
</div>