方法一文字居中text-align:center;line-height设置为父元素的height
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
background-color: #ccc;
width: 500px;
height: 500px;
text-align: center;
}
p {
line-height: 500px;
}
</style>
</head>
<body>
<div class="box">
<p>1111</p>
</div>
</body>
</html>
方法二单个块级 transform父元素设置为相对定位,子元素设置为绝对定位高度,宽度为50%
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
background-color: #ccc;
width: 500px;
height: 500px;
position: relative;
}
.box2 {
position: absolute;
top: 50%;
left: 50%;
background-color: black;
width: 200px;
height: 200px;
transform:translateX(-50%) translateY(-50%);
}
</style>
</head>
<body>
<div class="box">
<div class="box2"></div>
</div>
</body>
</html>
方法三单行行内元素:父元素设置:text-align:center,display:table-cell;vertical-align:middle,在这里,图片,文字,都是一样的操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
background-color: #ccc;
width: 500px;
height: 500px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
img {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="box">
<img src="5.png" alt="">
</div>
</body>
</html>
方法四flex实现不定宽度水平+垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
background-color: green;
height: 300px;
width: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.box2, .box3, .box4 {
background-color: red;
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<div class="box">
<div class="box2"></div>
</div>
</body>
</html>
https://github.com/7117/frontendCollection/tree/master/CSS