欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」行内元素以及块级元素的 水平垂直居中方法

作者 : 自学哈 本文共1102个字,预计阅读时间需要3分钟 2023-07-26 共94人阅读
也想出现在这里? 联系我们

行内元素

line-height:内容高度;
tex-align:center;

块级元素

1.定位+margin方法

定位上下左右值为0,然后margin:auto实现

 .fa{//父元素设置定位
            position: relative;
            width: 500px;
            height: 500px;
            background-color:#eee
            }
         .son{//子元素设置属性上下左右值为0,margin:auto
            position:absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
            margin: auto;
            width:20px;
            height:50px;
            background-color:#999;
            }

2.定位+margin/tansform方法

子元素在定位下移动父盒子一半宽高,再通过margin操作向反方向移动半个子盒子的宽高

 .fa{
            position: relative;
            width: 500px;
            height: 500px;
            background-color:#eee
            }
            .son{
            position:absolute;
            top:50%;
            left:50%;
            margin-top: -10px;
            margin-left: -25px;
            width:20px;
            height:50px;
            background-color:#999;
            }

通过transform:tanslateX()/translateY()反方向移动半个子盒子的宽高实现

.fa{
            position: relative;
            width: 500px;
            height: 500px;
            background-color:#eee
            }
        .son{
            position:absolute;
            top:50%;
            left:50%;             
            width:20px;
            height:50px;
            background-color:#999;
            transform: translateX(-10px);
            transform:translateY(-25px);           
            }

3.flex方法
父盒子设置flex:flex;设置主轴居中justify-content:center;侧轴居中align-items:center;

   .fa{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 500px;
            height: 500px;
            background-color:#eee
            }
        .son{            
            width:20px;
            height:50px;
            background-color:#999;
            transform: translateX(-10px);
            transform:translateY(-25px);           
            }

 

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」行内元素以及块级元素的 水平垂直居中方法
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号