5个技巧让你轻松做到div元素的水平垂直居中
最编程
2024-08-08 19:31:44
...
原创不易,求一键三连!!!
1.运用absolute和calc垂直居中
<style>
*{
padding: 0;
margin: 0;
}
.demo{
width: 300px;
height: 300px;
background-color: red;
position: absolute;
top: calc(50% - 150px);
left: calc(50% - 150px);
}
</style>
<body>
<div class="demo"></div>
</body>
2.运用flex布局进行垂直居中
<style>
*{
padding: 0;
margin: 0;
}
body{
//必须标明父盒子的具体高度,有局限性
height: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.demo{
width: 300px;
height: 300px;
background-color: red;
}
</style>
<body>
<div class="demo"></div>
</body>
3.运用absolute进行垂直居中
<style>
*{
padding: 0;
margin: 0;
}
.demo{
width: 300px;
height: 300px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin: -150px 0 0 -150px;
}
</style>
<body>
<div class="demo"></div>
</body>
4.运用margin:auto进行垂直居中
<style>
*{
padding: 0;
margin: 0;
}
.demo{
width: 300px;
height: 300px;
background-color: red;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<body>
<div class="demo"></div>
</body>
5.运用transform+absolute实现的居中
<style>
* {
padding: 0;
margin: 0;
}
.demo {
width: 300px;
height: 300px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
</style>
<body>
<div class="demo"></div>
</body>
统一效果图如下:
上一篇: 如何实现DIV元素的水平和垂直居中效果?