前端项目开发时,我们在页面布局的时候,经常会遇到让一个元素水平垂直居中,实现的方式很多,下面就来简单总结下,直接上代码,需要的可以直接使用:
方式1
<body>
<div class="wrap"></div>
</body>
.wrap{
width: 100px;
height: 100px;
position: absolute;
left: 0px;
right: 0px;
bottom: 0px;
top: 0px;
margin: auto;
background: red;
}
需要注意的是,当我们的页面有滚动条的时候,我们需要将绝对定位修改为固定定位。
方式2
<body>
<div class="wrap"></div>
</body>
html,body{
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
body{
display: flex;
align-items: center;
justify-content: center;
}
.wrap{
width: 100px;
height: 100px;
background-color: red;
}
方式3
html,body{
margin: 0;
padding: 0;
}
.wrap{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
方式4
html,body{
margin: 0;
padding: 0;
}
.wrap{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}
以上就是元素水平垂直居中的几种方式,希望对你有所帮助。