美文网首页
css居中未知宽高的盒子的多种方法

css居中未知宽高的盒子的多种方法

作者: 韩小强 | 来源:发表于2018-02-23 11:45 被阅读0次
    • 使用定位结合c3属性(不知宽高)
    .box {
          border: 2px solid #000;
          height: 500px;
          position: relative;
        }
        .div1 {
          border: 1px solid red;
          background: yellowgreen;
          position: absolute;  /*定位后转化为块元素,无需考虑是否是块元素*/
          top:50%;
          left:50%;
          transform:translate(-50%,-50%);
        }
    
    • 使用定位(已知高度)
     #box{
          width: 100px;
          height: 100px;
          background: #ccc;
          position:relative;
        }
        #div2{
          height: 20px;
          background: #f00;
          position:absolute;
          left:50%;
          top:50%;
          margin-left:-10px; /* 知道自己大小的情况,自身高度的一半 */
          margin-top:-10px; /* 知道自己大小的情况,自身高度的一半 */
        }
    
    • 不使用定位(行内元素)
    .box {
          border: 2px solid #000;
          height: 500px;
          text-align: center;
          line-height: 500px;
        }
        .div1 {
          border: 1px solid red;
          background: yellowgreen;
        }
    
    • 转化为table
     #vc {   /*父*/
          display:table; 
          background-color:#C2300B; 
          width:500px; 
          height:200px; 
          overflow:hidden; 
          margin-left:50px; 
          _position:relative;   /*针对ie6的hack*/
        }   
        #vci {  /*子*/
          vertical-align:middle; 
          display:table-cell;  
          _position:absolute; 
          _top:50%; 
        }   
        #content {     /*孙*/
          color:#fff; 
          border:1px solid #fff;  
          _position:relative; 
          _top:-50%;  
        }  
    
    • 旧弹性盒(针对老版本浏览器)
    {
    width:350px;
    height:100px;
    border:1px solid black;
    /* W3C */
    display:box;
    box-pack:center;
    box-align:center;  
    
    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;
    
    /* Safari, Chrome, and Opera */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    }
    ```
    

    相关文章

      网友评论

          本文标题:css居中未知宽高的盒子的多种方法

          本文链接:https://www.haomeiwen.com/subject/ufatxftx.html