div+cssはどのように1つの小さいdivを別の大きいdivの中で垂直に水平に中央に置くことができます

2130 ワード

出典を転載する.
方法1:
.parent {
          width:800px;
          height:500px;
          border:2px solid #000;
          position:relative;
}
 .child {
            width:200px;
            height:200px;
            margin: auto;  
            position: absolute;  
            top: 0; left: 0; bottom: 0; right: 0; 
            background-color: red;
}

方法2:(使いにくい)
.parent {
            width:800px;
            height:500px;
            border:2px solid #000;
            display:table-cell;
            vertical-align:middle;
            text-align: center;
        }
        .child {
            width:200px;
            height:200px;
            display:block;
            background-color: red;
        }

方法3:
.parent {
            width:800px;
            height:500px;
            border:2px solid #000;
            display:flex;
            justify-content:center;
            align-items:center;
        }
        .child {
            width:200px;
            height:200px;
            background-color: red;
        }

方法4:
.parent {
            width:800px;
            height:500px;
            border:2px solid #000;
            position:relative;
        }
        .child {
            width:300px;
            height:200px;
            position:absolute;/* 50%, */
            left:50%;            
            top:50%;
            transform:translateX(-50%) translateY(-50%);       //  margin-left: -150px;            margin-top:-100px;
            background-color: red;       
         }
本文は原文に対して少し修正があって、記録して探しやすいです.