html:
<!DOCTYPE html>
<html>
<head>
<title>CSS 居中</title>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
css:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
height: 100vh;
}
.box {
width: 20px;
height: 20px;
background-color: lightblue;
}
方法一:使用 flex 布局
在 .container
添加以下 css
display: flex;
justify-content: center;
align-items: center;
方法二:使用 grid 布局
在 .container
添加以下 css
display: grid;
justify-content: center; /* can be replaced by justify-items */
align-items: center; /* can be replaced by align-content */
方法三:使用 position 属性
在 .container
添加以下 css
position: relative;
在 .box
添加以下 css
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
方法四:使用 margin 属性
在 .container
添加以下 css
display: flex;
在 .box
添加以下 css
margin: auto auto;
方法五:使用 ::before 元素
在 .container
添加以下 css
text-align: center;
向 .container
元素的开始位置添加一个 ::before
inline 元素,其中 margin-right: -.25em;
是为了抵消 ::before
产生的空格
.container::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -.25em; /* mitigate the spawned single blank space */
}
在 .box
添加以下 css
display: inline-block;
vertical-align: middle;
注意纵向居中需要 .container
元素里的 height
类型为 <length>
(a definite length).