块元素,且宽和高已知
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body, .father {
width: 100%;
height: 100%;
}
.father {
position: relative;
}
.child {
/* 使用绝对定位 */
position: absolute;
left: 50%;
top: 50%;
/* 盒子宽和高的一半 */
margin-left: -150px;
margin-top: -150px;
width: 300px;
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
块元素,且宽和高未知
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body, .father {
width: 100%;
height: 100%;
}
.father {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
/* 偏移50% */
transform: translateX(-50%) translateY(-50%);
width: 300px;
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</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">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body, .father {
width: 100%;
height: 100%;
}
.father {
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 300px;
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
margin:auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html, body, .father {
width: 100%;
height: 100%;
}
.father {
position: relative;
}
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 300px;
height: 300px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
以上四种居中的方式都为下图
行内元素或行内块元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.father {
width: 500px;
height: 500px;
background-color: #cccccc;
}
.father {
text-align: center;
line-height: 500px;
}
.child {
font-size: 26px;
color: #f40;
display: inline-block;
}
</style>
</head>
<body>
<div class="father">
<div class="child">一朵菊花,一个小鬼</div>
</div>
</body>
</html>