div水平居中的4种最简单方法

174 阅读1分钟
1. 绝对定位方法
    .cont{
        width:200px;  
        height:200px;  
        background: red;
        position:absolute;  
        left:50%;  
        top:50%; 
        margin-left: -100px;
        margin-top: -100px; 
    }
2.  绝对定位+transform
    .cont{
        width:200px;  
        height:200px;  
        background: red;
        position:absolute;  
        left:50%;  
        top:50%;  
        transform: translate(-50%, -50%);
    }
3. 绝对定位2
    .cont2{
        width: 200px;
        height: 200px;
        background:blue;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
    }
4. 弹性布局
    <style>
        html,body{
				width: 100%;
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			.box{
				width: 200px;
				height: 200px;
				background: green;
			}
    </style>