CSS如何实现垂直居中?

通过vertical-align: middle

注意:vertical-align: middle生效的元素必须是 display: inline-block;且必须有一个兄弟元素做参照(其原理是寻找兄弟元素中最高的元素做参照让自身的中点高度和参照的中点高度对齐)

<style>
        .box1 {
            width: 600px;
            height: 300px;
            background-color: aqua;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: black;
            display: inline-block;
            vertical-align: middle;
        }

        .box3 {
            background-color: brown;
            width: 0px;
            height: 100%;
            display: inline-block;
            vertical-align: middle;
        }
    </style>
View Code
<body>
    <div class="box1">
        <div class="box2"></div>
        <div class="box3"></div>
    </div>
</body>

通过display: flex

注意:给父元素display: flex;给目标元素align-self: center

 <style>
        .box1 {
            width: 600px;
            height: 300px;
            background-color: aqua;
            display: flex
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: black;
            align-self: center;
        }

    </style>
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>

通过line-height

注意:此方法以只父元素height,然后让目标元素的line-height等于父元素height;适用于目标元素为文本的时候

    <style>
        .box1 {
            width: 600px;
            height: 300px;
            background-color: aqua;
            display: flex
        }

        .box2 {
            line-height: 300px;
            width: 50%;
            height: 50%;

        }

    </style>
<body>
    <div class="box1">
        <p class="box2">123456</p>
    </div>
</body>

通过transform和绝对定位

注意:此时未知父元素高度;那么就需要先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中:

    <style>
        .box1 {
            width: 600px;
            height: 300px;
            background-color: aqua;
            position: relative;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: beige;
            position: absolute;
            top: 50%;
            transform: translate(0, -50%);

        }

    </style>
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>

 

posted @ 2022-09-21 20:04  天青色等烟雨灬  阅读(105)  评论(0)    收藏  举报