div中的div居中對齊 div中div垂直居中對齊



文章插圖
div中的div居中對齊 div中div垂直居中對齊

文章插圖
【div中的div居中對齊 div中div垂直居中對齊】方法一
#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;//子元素垂直居中