灌木大叔

每一个不曾起舞的日子都是对以往生命的辜负!!

  :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

第一种:给父级设置宽高100%,div设置绝对定位,left,right,top,bottom设置为0,margin:auto即可实现

//布局 style
*{
margin: 0;
padding: 0;
}
body,html{
width: 100%;
height: 100%;
position: relative;
}
.div{
position: absolute;
width: 200px;
height: 200px;
background: salmon;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
//body
<body>
<div class="div"></div>
</body>
第二种:利用绝对定位和tranform(过渡动画)实现,div绝对定位,left: 50%; top: 50%;然后设置 transform: translate3d(-50%,-50%,0);即可

<style>
*{
margin: 0;
padding: 0;
}
body,html{
width: 100%;
height: 100%;
position: relative;
}
.div{
position: absolute;
width: 200px;
height: 200px;
background: salmon;
left: 50%;
top: 50%;
transform: translate3d(-50%,-50%,0);
}
</style>
//body
<body>
<div class="div"></div>
</body>
第三种:flex弹性盒布局,给父级div设置display:flex,设置水平和垂直居中 justify-content: center; align-items: center;

//style
.div{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.box{
width: 200px;
height: 200px;
background: sandybrown;
}
//body
<body>
<div class="div">
<div class="box"></div>
</div>
</body>
第四种:div设置绝对定位,left: 50%; top: 50%距离左和上是margin-left:calc(-div自身宽度/2),margin-top:calc(-div自身高度/2),也可以自己计算margin-left和margin-top的值

//style
<style>
*{
margin: 0;
padding: 0;
}
body,html{
width: 100%;
height: 100%;
position: relative;
}
.div{
position: absolute;
width: 200px;
height: 200px;
background: salmon;
left: 50%;
top: 50%;
margin-left:calc(-200px/2);
margin-top: calc(-200px/2);
}
</style>
//body
<div class="div">
<div class="box"></div>
</div>
以上就是四种方法的实现
有不对的请指教~

作者:X_8d6a
链接:https://www.jianshu.com/p/06b4f65a16e6
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2021-07-09 08:39  灌木大叔  阅读(11373)  评论(0编辑  收藏  举报