前端面试~2020~垂直水平居中布局~多种方法

it2023-02-25  86

HTML代码:

<div class="box1"> <div class="box2"> </div> </div> 方法一 Flex布局 .box1{ background-color:red; width:200px; height:200px; display:flex; flex-direction: row; justify-content:center; align-items:center; } .box2{ background-color:green; width:100px; height:100px; }  方法二 绝对定位 (使用于知道子DOM的长宽) .box1{ background-color:red; width:200px; height:200px; position:relative; } .box2{ background-color:green; width:100px; height:100px; position:absolute; margin-top:50%; margin-left:50%; left:-50px; top:-50px; }  方法三 绝对定位 (不必知道子DOM长宽)

 

.box1{ background-color:red; width:200px; height:200px; position:relative; } .box2{ background-color:green; width:100px; height:100px; position:absolute; left:50%; top:50%; transform:translate(-50%,-50%) } 方法四 绝对定位  .box1{ background-color:red; width:200px; height:200px; position:relative; } .box2{ background-color:green; width:100px; height:100px; position:absolute; margin:auto; left:0; top:0; right:0; bottom:0; }

 

最新回复(0)