CSS块级元素水平垂直居中常用的几种方式

编程入门 行业动态 更新时间:2024-10-16 02:23:43

提示:本文总结了在工作中常用的4种块级元素水平垂直居中方法,希望对你有所帮助

一、使用flex布局(无敌)

<body>
    <div class="father">
        <div class="child"></div>
    </div>
</body>

<style>
    .father {
        width: 300px;
        height: 300px;
        border: 2px solid red;
        display: flex; 
        justify-content: center;
        align-items: center;
    }
    .child {
        width: 100px;
        height: 100px;
        background-color: #ccc;
    }
</style>

  效果图:

此方法是本鹅工作中最常用的也是最好用的,推荐大家使用!

对flex布局有兴趣研究的伙伴可以参考阮一峰大佬的博客:

Flex 布局教程:语法篇 - 阮一峰的网络日志


二、使用定位(子绝父相) + css3的translate平移属性

<body>
    <div class="father">
        <div class="child"></div>
    </div>
</body>

<style>
    // 效果图同一
    .father {
        width: 300px;
        height: 300px;
        border: 2px solid red;
        position: relative;
    }
    .child {
        position: absolute;
        width: 100px;
        height: 100px;
        top: 50%;
        left: 50%;  // top:50%  left:50% 之后,此时子盒子的左上角顶点处于父盒子的中心位置
        transform: translate(-50%,-50%);  // 平移子盒子自身的50%即可
        background-color: #ccc;
    }
</style>

效果图同一


 三、使用定位(子绝父相)+ margin: auto

<body>
    <div class="father">
        <div class="child"></div>
    </div>
</body>

<style>
    .father {
        width: 300px;
        height: 300px;
        border: 2px solid red;
        position: relative;
    }

    .child {
        width: 100px;
        height: 100px;
        margin: auto;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
    }
</style>
注意: 
1、margin: auto是具有强烈计算意味的关键字,用来分配元素对应方向上的剩余空间。例如margin:10px,等同于margin-top:10px;margin-left:10px;margin-right:10px;margin-bottom:10px

2、不使用定位的情况下,margin:auto 只能使块级元素水平居中,不能实现垂直居中,因为垂直方向上默认没有剩余的空间。margin: auto = margin: 0 auto

3、有了绝对定位后,margin-top和margin-bottom 的值就不是0了,也是通过计算所得。所以可以实现垂直居中

四、 flex布局 + margin: auto

<body>
    <div class="father">
        <div class="child"></div>
    </div>
</body>

<style>
    .father {
        width: 300px;
        height: 300px;
        border: 2px solid red;
        display: flex;
    }

    .child {
        width: 100px;
        height: 100px;
        margin: auto;
        background-color: #ccc;
    }
</style>

效果图同一

此方法是代码量最少的一个,原理类似方法三

更多推荐

CSS块级元素水平垂直居中常用的几种方式

本文发布于:2023-06-13 12:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1381939.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几种   元素   水平   常用   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!