1: 第一种方法:
<div class="parent"> // 父级盒子
<div class="child"><div> // 子级盒子
</div>
<style>
.parent {
width: 500px;
height: 500px;
border: 1px solid #ccc;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #eee;
}
</style>
---------------------------------------------
第一中方法:
利用定位 (常用方法)
.parent {
position:relative;
}
.child { // 子绝父相
position:absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
// 定位的原理就是定位中心的盒子在左上顶点, 所以定位之后我们只需要退回盒子一半距离。
----------------------------------------------
第二种方法: 利用内盒子margin: auto;
.parent {
position:relative;
}
.child {
position:absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
// CSS中margin:auto什么意思?margin:auto属性的用法详解
margin:auto可以让元素水平居中的, margin:auto可以让元素水平居中的原因。 auto: 是最常用的用法: 通过分配auto元素的左右边距, 它们可以平等地占据元素容器中的可用水平空间
-----------------------------------------------------------------
第三种方法:
父元素设置display 属性, 设置垂直 水平居中
.parent {
display: flex;
justify-content: center; // 水平居中
align-items: center; // 垂直居中
}
---------------------------------------------------------------
第四种方法: 利用display: table-cell
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
}
组合使用display: table-cell 和 vertical-align, text-align, 使父元素所有元素, 所有元素行内元素垂直水平居中(内部的div设置 display: inline-block即可)
---------------------------------------------------------------
第五种方法:
.parent {
position: relative;
}
.child {
positon: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
--------------------------------------------------------------
第六中方法: 利用calc 计算
.parent {
positon:relative;
}
.child {
positon: absolute;
top:cale(200px); // (父元素高 - 子元素高) / 2 = 200px;
left: cale(200px); // (父元素宽 - 子元素宽) / 2 = 200px;
}