css 水平垂直居中

1、flex 方式

有效的代码是这三行,这样的话就是在主轴上和交叉轴上都是居中的,实现了水平垂直居中,这种方式应该是几种里面最简单的,而且是弹性布局,不需要知道宽高。不过这个是有兼容性的问题,老版本的IE不要用。
flex布局不知道的话可以看一下菜鸟的那个教程,这是网址,根据它的解释,有什么不懂得点查一下基本就行了。
https://www.runoob.com/w3cnote/flex-grammar.html

display: flex;
justify-content: center;
align-items: center;
<style>
        .box{
            height: 300px;
            width: 500px;
            background: deeppink;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .box-child{
            background: pink;
        }
    </style>

    <div class="box">
        <div class="box-child">
            luluwang
        </div>
    </div>

2、定位方式

1、绝对定位,50%减自身宽高

这个方法的好处就是不需要知道具体的宽高,根据比例来算,不能用flex的话用这个也挺好的

    <style>
        .box {
            position: absolute;
        }
        .box-child {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>

    <div class="box">
        <div class="box-child">
            luluwang
        </div>
    </div>
2、绝对定位,上下左右全0,margin:auto

这种方法也是利用的定位,虽然没有考虑宽高是多少,但是必须要有宽高

<style>      
        .box{
            position: relative;
        }
        .box-child{
            position: absolute;
            height: 100px;
            width: 150px;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
        }
    </style>
    <div class="box">
        <div class="box-child">
            luluwang
        </div>
    </div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值