前端学习之CSS如何实现元素的水平垂直居中:
目录(共整理5种方法,欢迎讨论、补充)
1.利用CSS3的flex:
父元素设置display属性为flex,
justify-content与align-items属性都设置为center
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素垂直居中</title>
<!-- 利用flex -->
<style>
.father {
width: 500px;
height: 500px;
background: #000;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 100px;
height: 100px;
background: #f00;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
2.利用绝对定位和margin属性或transform属性:
子元素绝对定位
设置top、left属性为50%
再设置margin为负一半的宽高
或直接使用transform属性设置,即使宽高未知也可以实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>元素垂直居中</title>
<!-- 利用绝对定位 -->
<style>
.father {
position: relative;
width: 500px;
height: 500px;
background: #000;
}
.son {
position: absolute;
width: 100px;
height: 100px;
background: #f00;
top: 50%;
left: 50%;
/* margin: -50px -50px -50px -50px; */
/* 或 */
/* margin-top: -50px;
margin-left: -50px; */
/* 当宽高未知时 */
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
3.利用绝对定位和“margin: auto;”:
子元素绝对定位,设置top、right、bottom、left都为0
设置margin为auto
<!-- 利用margin auto -->
<style>
.father {
position: relative;
width: 500px;
height: 500px;
background: #000;
}
.son {
position: absolute;
width: 100px;
height: 100px;
background: #f00;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
</style>
4.利用display属性为table-cell
父元素display属性为table-cell
vertical-align: middle;
text-align: center;
子元素display属性为inline-block
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>元素垂直居中</title>
<!-- 利用table-cell -->
<style>
.father {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 500px;
height: 500px;
background: #000;
border: 1px solid #000;
}
.son {
width: 100px;
height: 100px;
background: #f00;
display: inline-block;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
5.利用flex,从子元素下手
第一种方法中我们从父元素下手设置了align-items和justify-context属性为center
这一次我们从子元素下手
同样将父元素设置为flex,justify-content属性设为center,但是不设置align-items属性
然后设置子元素align-self属性为center,该属性可以允许单个项目有与其他项目不一样的对齐方式,可覆盖父元素设置的align-items属性
<!-- 利用flex 子元素 -->
<style>
.father {
width: 500px;
height: 500px;
background: #000;
display: flex;
justify-content: center;
}
.son {
width: 100px;
height: 100px;
background: #f00;
align-self: center;
}
</style>