cssdiv整體水平居中(CSSDIV上下左右居中)
2023-10-23 03:23:22 3
cssdiv整體水平居中?方法一#wrap{ position:absolute; width:300px; height:200px; top:50%; left:50%; transform:translate(-50%,-50%) ; background:#009688; } 若是下面的代碼,其結果就是錯誤的,現在小編就來說說關於cssdiv整體水平居中?下面內容希望能幫助到你,我們來一起看看吧!
cssdiv整體水平居中
方法一
#wrap{ position:absolute; width:300px; height:200px; top:50%; left:50%; transform:translate(-50%,-50%) ; background:#009688; } 若是下面的代碼,其結果就是錯誤的
#wrap{ width:300px; height:200px; margin-top:50%; margin-left:50%; transform:translate(-50%,-50%) ; background:#009688; }
原因:
當margin設置成百分數的時候,其top right bottom left的值是參照父元素盒子的寬度進行計算
方法二
直接用彈性盒布局,作用於父元素上實現
parent{ width:100%; height:100vh; display:flex; justify-content: center;//子元素水平居中 align-items: center;//子元素垂直居中 }
,