原文出处,在此作为分享 🧐
文中从CSS的 position 属性、Flexbox 和 Grid 三个方面来探索如何让一个 子div
实现相对 父div
居中。
实现效果:
页面基本结构样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>示例</title>
<style>
.parent {
width: 200px;
height: 200px;
background-color: #b0e0e6;
}
.child {
width: 100px;
height: 100px;
background-color: #66cdaa;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
一、使用CSS的 position 属性实现 div 居中
1.1 使用 position: relative、absolute 以及 top、left 偏移值
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
1.2 使用 position: relative 和 absolute, top、left、right 和 bottom 偏移值以及 margin: auto
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
如果我们只设置了top: 0
、bottom: 0
以及margin: auto
,子元素就会垂直居中。
同样,如果我们只设置了left: 0
、right: 0
以及margin: auto
,子元素就会水平居中。
二、使用 CSS 中 Flexbox 实现 div 居中
2.1 使用Flexbox、 justify-content 和 align-item
.parent {
display: flex;
justify-content: center;
align-items: center;
}
2.2 使用Flexbox、justify-content 和 align-self
.parent {
display: flex;
justify-content: center;
}
.child {
align-self: center;
}
2.3 使用Flexbox 和 margin: auto
.parent {
display: flex;
}
.child {
margin: auto;
}
三、使用 CSS 中 Grid 实现 div 居中
3.1 使用 Grid、justify-content 和 align-items
.parent {
display: grid;
justify-content: center;
align-items: center;
}
3.2 使用 Grid 和 place-items
.parent {
display: grid;
place-items: center;
}
3.3 使用Grid、align-self 和 justify-self
.parent {
display: grid;
}
.child {
justify-self: center;
align-self: center;
}
3.4 使用 Grid 和 place-self
.parent {
display: grid;
}
.child {
place-self: center;
}
3.5 使用 Grid 和 margin: auto
.parent {
display: grid;
}
.child {
margin: auto;
}
如我们期望的那样,所有方法都会得到相同的结果:
总结
本文讨论了10种将 div
居中的方法,包括:
- 使用position: relative、absolute和top、left偏移值
- 使用position: relative和absolute、top、left right和bottom偏移值和margin: auto
- 使用flexbox、justify-content、 align-item
- 使用flexbox、justify-content和align-self
- 使用flexbox和margin: auto
- 使用grid justify-content和align-items
- 使用grid和place-items
- 使用grid、align-self和justify-self
- 使用grid和place-self
- 使用grid和margin: auto