zoukankan      html  css  js  c++  java
  • 不定宽高的div水平、垂直居中问题

    HTML代码如下:

    <div id="box">
      <div id="content"></div>
    </div>

    方法一(最佳兼容,IE7以上都可以):

        #box {
            width: 100px;
            height: 100px;
            position: relative;
        }
    
        #content {
            width: 50px;
            height: 50px;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
        }

     这里的content的宽高是可以不固定的,关键点是:绝对定位后上下左右都给0,并且margin:0,效果可以看下面这个:

    演试

    方式二(实现最佳):

        #box {
            width: 100px;
            height: 100px;
            position: relative;
        }
    
        #content {
            position: absolute;
            width: 50px;
            height: 50px;
            left: 50%;
            top: 50%;
            -webkit-transform: translateX(-50%) translateY(-50%);
            transform: translateX(-50%) translateY(-50%);
        }

    演试

    方法三(代码最简单):

        #box {
            width: 200px;
            height: 200px;
            display: -webkit-flex;
            display: flex;
            justify-content: center;
            align-items: center;
        } 

    演试

  • 相关阅读:
    Co.
    编程
    编程
    编程
    数据同步
    Co.
    Co.
    Co.
    Co.
    sss
  • 原文地址:https://www.cnblogs.com/johnjackson/p/10872591.html
Copyright © 2011-2022 走看看