第一种方法:弹性盒flexbox
<style>
div {
display: flex;
主轴水平居中
justify-content: center;
交叉轴水平居中
align-items: center;
width: 300px;
height: 300px;
border: 1px solid red;
}
p {
width: 100px;
height: 100px;
background-color: green;
}
</style>
<body>
<div>
<p></p>
</div>
</body>
第二种方法:position定位
<style>
div {
相对定位
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
p {
绝对定位
position: absolute;
走父元素上面的一半
top: 50%;
走父元素左边的一半
left: 50%;
走自身高度的一半像素
margin-top: -50px;
走自身宽度的一半像素
margin-left: -50px;
width: 100px;
height: 100px;
background-color: green;
}
</style>
<body>
<div>
<p></p>
</div>
</body>
第三种方法:定位position
<style>
div {
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
p {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: green;
}
</style>
<body>
<div>
<p></p>
</div>
</body>
第四种方法:
div {
width: 300px;
height: 300px;
border: 1px solid red;
text-align: center;
line-height: 300px;
}
p {
转为行内快元素
display: inline-block;
width: 100px;
height: 100px;
background-color: green;
文本垂直居中
vertical-align: middle;
}
<body>
<div>
<p></p>
<span></span>
</div>
</body>
第五种方法:
.box {
width: 300px;
height: 300px;
border: 1px solid #000;
/* 网格布局 */
display: grid;
/* 设置3行高度均为100px */
grid-template-rows: repeat(3,100px);
/* 设置3列高度均为100px */
grid-template-columns: repeat(3,100px);
grid-template-areas: ". . ." ". a ." ". . .";
}
.small {
width: 100px;
height: 100px;
background-color: red;
grid-area: a;
}
<div class="box">
<div class="small"></div>
</div>