1、行内联元素或文字在父级中水平垂直居中的方法
/* 水平居中 / :text-align: center;
/ 垂直居中 */:line-height: 200px;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d1 {
width: 400px;
height: 200px;
/* 水平居中 */
text-align: center;
/* 垂直居中 */
line-height: 200px;
background-color: yellow;
}
.d1 span {
background-color: red;
}
</style>
</head>
<body>
<!-- 一行内联元素或文字在父级中水平垂直居中的方法 -->
<div class="d1">
<span>内联元素居中</span>
</div>
</body>
</html>
2、块级元素在父级中水平垂直居中的方法:
2.1、在父级设置相对定位,子级设置绝对定位
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d2 {
width: 400px;
height: 200px;
background-color: blue;
position: relative;
}
.d2 div {
width: 120px;
height: 100px;
background-color: greenyellow;
/* 定位在父元素中 */
position: absolute;
top:50%;
/* 回调子元素高度的一半 */
margin-top: -50px;
left: 50%;
/* 回调子元素宽度的一半 */
margin-left: -60px;
}
</style>
</head>
<body>
<!-- 块级元素在父级中水平垂直居中的方法 -->
<div class="d2">
<div>块级元素居中</div>
</div>
</body>
</html>
2.2、也可使用transform的translate属性
transform:translate(-50%,-50%);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.d2 {
width: 400px;
height: 200px;
background-color: blue;
position: relative;
}
.d2 div {
width: 120px;
height: 100px;
background-color: greenyellow;
/* 定位在父元素中 */
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<!-- 块级元素在父级中水平垂直居中的方法 -->
<div class="d2">
<div>块级元素居中</div>
</div>
</body>
</html>