Navigation

    GitHub中文社区
    • GitHub排行榜

    论坛

    • Login
    • Categories
    • Recent
    • Tags
    • Popular

    盒子如何垂直水平居中方法

    技术交流
    3
    4
    300
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • xiongbofan
      xiongbofan last edited by admin

      盒子垂直水平居中方法:
      1、

      .box{
        position: absolute;
        top:0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
      }
      

      2、使用定位垂直水平居中:负margin居中(传统方法)
      子绝父相

      .father{
        position:relative;
        width:300px;
        height:300px;
      }
      .son{
        position: absolute;
        width:100px;
        height:100px;
        left:50%;
        top:50%
        margin-left: -50%;
        margin-top: -50%;
      }
      

      3.transform居中方法

      .box {
        width: 100px;
        height: 100px;
        position: relative;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
      }
      

      个人觉得比较好用的垂直居中方法,还是定位和transform粗体字

      yashugongshang 1 Reply Last reply Reply Quote 1
      • loveme199
        loveme199 last edited by

        直接用flex更好

        .container {
            display: flex;
            align-items: center;
            height: 600px;
            border: 2px solid #006100; 
        }
        
        <div class="container">
            <div class="centered-element">
              <p>I'm a Camper, and I'm vertically centered</p>
            </div>
        </div>
        
        xiongbofan 1 Reply Last reply Reply Quote 0
        • xiongbofan
          xiongbofan @loveme199 last edited by

          @loveme199 ok

          1 Reply Last reply Reply Quote 0
          • yashugongshang
            yashugongshang @xiongbofan last edited by

            @xiongbofan 学到老,活到老

            学而不思则罔,思而不学则殆

            1 Reply Last reply Reply Quote 0
            • First post
              Last post