1. 行内元素:
line-height
text-align:center;
line-height:同父元素高度;
z注意:
① line-height对inline元素生效,如span文本;无法设置inline-block,如img图片
② 行高对多行有效,所以多行不要用
2. 块级元素:
(1) flex
display:flex;
justify-content:center;
align-items:center;
(2) 定位
/* 方法一: */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 方法二: */
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
3. 例子
<!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>Document</title>
<style>
* {
margin: 0;
}
body {
height: 100vh;
background-color: orange;
position: relative;
}
.scarf {
height: 200px;
width: 800px;
text-align: center;
background-color: pink;
/* 定位法一 */
/* position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); */
/* 定位法二 */
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
.scarf span {
/* line-height: 200px; */
background-color: violet;
}
</style>
</head>
<body>
<div class="scarf">
<span>这个一行文本</span>
</div>
</body>
</html>