块级元素居中:
1.未知子元素宽高,绝对定位 + transform:translate
<!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>
.container {
position: relative;
width: 400px;
height: 400px;
background-color: blanchedalmond;
}
.item {
position: absolute;
/* 以左上顶点为基准 */
left: 50%;
top: 50%;
/* 往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置。 */
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
2.已知子元素宽高(绝对定位+margin 负值应用)
<!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>
.container{
width: 400px;
height: 400px;
background-color: aqua;
position: relative;
}
.item{
/* 已知子元素宽高 */
position: absolute;
left: 50%;
top: 50%;
/* margin-left和margin-top: 为负值,则向左边,上面移动 */
margin-left: -100px;
margin-top: -100px;
width: 200px;
height: 200px;
background-color: bisque;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
3.父盒子:dispaly:flex
<!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>
.container {
display: flex;
/* 主轴:水平 */
justify-content: center;
/* 副轴:竖直 */
align-items: center;
/* 可以通过flex-direction 来更改主轴 */
width: 400px;
height: 400px;
background-color: blanchedalmond;
}
.item {
width: 200px;
height: 200px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
行内元素居中:
<!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>
.container{
width: 400px;
height: 400px;
background-color: blanchedalmond;
text-align: center;
line-height: 400px;
}
.item{
background-color: blue;
font-size: 70px;
color: white;
}
</style>
</head>
<body>
<div class="container">
<a class="item" href='#'>点击跳转</a>
</div>
</body>
</html>