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 @   天青色等烟雨灬  阅读(98)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示