CSS水平垂直居中方法總結
方案一:position絕對定位+margin負值
適用:子元素有寬高尺寸
方法:父元素相對定位,子元素絕對定位,left和top定位到父元素50%,再用margin向左和向上移動子元素尺寸的一半。
.wrapper{ background: #1890ff; height: 400px; width:400px; position: relative; } .content{ background: #FFB90F; width: 200px; height:200px; position: absolute; left: 50%; top:50%; margin:-100px 0 0 -100px; }
效果:

方案一
方案二:position絕對定位+transform調整位置
適用:子元素未知寬高(當然知道也可以啦!)
方法:此方法與方案一是一個道理,將margin換為transform:translate(-50%,-50%)。
.wrapper{ background: #1890ff; height: 400px; width:400px; position: relative; } .content{ background: #FFB90F; /*width: 200px;*/ /*height:200px;*/ position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); }
效果:

方案二.png
方案三:position絕對定位+margin:auto
適用:子元素有寬高尺寸
方法:父元素相對定位,子元素絕對定位,left、right、top、bottom設定為0,再用margin:auto。
.wrapper{ background: #1890ff; height: 400px; width:400px; position: relative; } .content{ background: #FFB90F; width: 200px; height:200px; position: absolute; left: 0; right:0; top:0; bottom:0; margin:auto; }
效果:與方案一相同。
方案四:flex彈性盒
適用:子元素未知寬高(當然知道也可以啦!)
方法:父元素設定為彈性盒,justify-content和align-items都設定為center居中。
.wrapper{ background: #1890ff; height: 400px; width:400px; display: flex; justify-content: center;/*主軸方向居中*/ align-items:center;/*側軸方向居中*/ } .content{ background: #FFB90F; /*width: 200px;*/ /*height:200px;*/ }
效果:與方案二相同。