让未知大小的盒子居中

方法1:

css:

 #box1 {            
     position: relative;            
     width: 600px;
     height: 600px;
     background: pink; 
 }
 #box2 {
     position: absolute;
     width: 300px;
     height: 300px;
     background: yellowgreen;
     top: 0;
     left: 0;
     bottom: 0;
     right: 0;
     margin: auto;
 }

html:


方法2:

使用CSS3属性

    #box2 {
         position: absolute;
         width: 300px;
         height: 300px;
         background: yellowgreen;
         top: 50%;
         left: 50%;
         transform: translate(-50% -50%);
        }

你可能感兴趣的:(让未知大小的盒子居中)