1 实现原理:
1 设置 .main 元素为相对定位 position: relative;,这样其子元素设置绝对定位时就相对它了。
2 然后设置 .content 元素为绝对定位 position: absolute; 并设置它的 top、left、bottom、right 都为0,
3 这样该元素的元素的尺寸表现为“格式化宽度和格式化高度”,和 <div> 的“正常流宽度”一样,同属于外部尺寸,
也就是尺寸自动填充父级元素的可用尺寸,但由于此时我们设置了 .content 元素的宽高,就限制了元素自动填充,
这样就多出来150px的空间了。
4 最后我们设置 .content 元素为 margin: auto; 此时根据 auto 的计算规则,将上下左右剩余空间全部等分了,
自然就居中了。代码如下
.main {
width: 300px;
height: 500px;
background-color: #50ba8b;
/*关键代码*/
position: relative;
}
.content {
width: 100px;
height: 100px;
background-color: #5b4d4e;
/*关键代码*/
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
2.
实现原理:
(1) 设置 .main 元素为相对定位 position: relative;,这样其子元素设置绝对定位时就相对它了。
(2) 然后设置 .content 元素为绝对定位 position: absolute; 并设置 top: 50%;、left: 50%;,
这样.content 元素的左上角就位于 .main 元素的中心了。
(3) 最后设置 .content 元素 transform: translate(-50%, -50%); 将自身左移及上移宽高的一半,
这样 .content 元素的中心处于 .main 元素的中心处,自然就实现了居中效果。
这种方法的好处就是不需要固定 .content 元素的宽高。代码如下
.main {
width: 300px;
height: 300px;
background-color: #50ba8b;
/*关键代码*/
position: relative;
}
.content {
width: 150px;
height: 150px;
background-color: #5b4d4e;
/*关键代码*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3. flex布局
.main {
width: 300px;
height: 300px;
background-color: #50ba8b;
/*关键代码*/
display: flex;
}
.content {
width: 150px;
height: 150px;
background-color: #5b4d4e;
/*关键代码*/
margin: auto;
}
4.flex布局
.content {
width: 150px;
height: 150px;
background-color: #5b4d4e;
/*关键代码*/
display: flex;
align-items: center;
justify-content: center;
margin: auto;
}
<div class="content">
<div>12313</div>
</div>