前端开发常用知识点一:如何设置子div在父div中垂直居中显示?

在前端开发中,要设置子div在父div中垂直居中的情况有很多,现通过学习一些博主的博客及日常项目实战,总结如下几种最常用的方法:

方法一:display:flex(这是小博主最常用的设置垂直居中的方法!)

            .parent {
                width: 300px;
                height: 200px;
                border: 1px solid red;
                display: flex;
                justify-content: center;  /*水平居中*/
                align-items: center;      /*垂直居中*/
            }
            .child {
                width: 100px;
                height: 100px;
                border: 1px solid violet;
            }

方法二:定位的方法

            .parent {
                width: 400px;
                height: 300px;
                border: 2px solid blue;
                position: relative;
            }
            .child {
                width: 150px;
                height: 100px;
                border: 1px solid pink;
                position: absolute;
                top: 50%;
                left:50%;
                margin-top: -50px;     /*这里是子div高的一半*/
                margin-left: -50px;    /*这里是子div宽的一半*/
            }            

适用情况:知道子div的宽高,可以不知道父div的宽高。

方法三:定位及margin: auto实现

            .parent {
                width: 300px;
                height: 200px;
                border: 1px solid red;
                position:relative;
             }
            .child {
                width: 100px;
                height: 100px;
                border: 1px solid violet;
                position: absolute;
                margin: auto;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
            }

方法四:display: table-cell

            .parent {
                width: 300px;
                height: 200px;
                border: 1px solid red;
                display: table-cell;
                vertical-align: middle;
                text-align: center;
            }
            .child {
                width: 100px;
                height: 100px;
                border: 1px solid violet;
                display: inline-block;
            }

方法五:计算四周的间距设置子元素与父元素之间的margin-top和margin-left(不推荐)

            .parent {
                width: 300px;
                height: 200px;
                border: 1px solid red;
            }
            .child {
                width: 100px;
                height: 100px;
                border: 1px solid violet;
                margin-top: 50px;
                margin-left: 100px;
            }

参考博客:小div在大div里面水平垂直都居中的实现方法_buyaoxx的博客-CSDN博客

专注前端,用心分享,欢迎关注我的个人微信公众号,定有收获。

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值