让盒子在网页中居中的方法

轩陌

分类: HTML/CSS 10263 2

让一个盒子居中的几种方法,通过绝对定位实现,会跟着浏览器窗口的缩放不断调整位置,一直居中

  1. 通过绝对定位,定位时上边距与左边距都给50%,在利用margin减去当前盒子的一半宽度与高度
    
    .box{
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        margin: -50px 0 0 -50px;
    }
    
  2. 通过绝对定位给4个方向都为0;用margin自动,实现居中
    
    .box {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        width: 100px;
        height: 100px;
        margin: auto;
    }
    
  3. 在不知道width、height的情况下,利用transform:translate(-50%, -50%)一样可以做到
    
    .box {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        transform: translate(-50%, -50%);
    }
    
  4. 通过 display: flex 实现居中
  5. 
    .box {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    

    DEMO展示

  • 24人 Love
  • 2人 Haha
  • 1人 Wow
  • 1人 Sad
  • 0人 Angry
css、css垂直居中、前端笔记

作者简介: 轩陌

打赏

生命的意义在于折腾,一直努力成长中,期待梦想实现的那刻。

共 2 条评论关于 “让盒子在网页中居中的方法”

Loading...