适用范围
仅居中元素定宽高适用
- absolute + 负margin
- absolute + margin auto
- absolute + calc
居中元素不定宽高
- absolute + transform
- flex
定义的盒子如下
<div class="wp">
<div class="box size">123123</div>
</div>
.wp {
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
.size {
width: 100px;
height: 100px;
background: green;
}
absolute + 负margin
.wp {
position: relative;
}
.box {
position: absolute;;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
absolute + margin auto
.wp {
position: relative;
}
.box {
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
absolute + calc
.wp {
position: relative;
}
.box {
position: absolute;;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
absolute + transform
.wp {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
flex
.wp {
display: flex;
justify-content: center;
align-items: center;
}
本文介绍五种使用CSS实现元素居中的方法:通过absolute定位结合负margin、margin auto、calc属性及transform属性,以及采用Flex布局方式。每种方法适用于不同场景下的居中需求。
1414

被折叠的 条评论
为什么被折叠?



