如何让元素居中
如何让元素居中
行内元素
水平居中
<div class="parent">
<span class="child">content</span>
</div>
-
text-align: center;
不改变父元素,让子元素居中
.parent {
background-color: red;
text-align: center;
}
-
width: fit-content;
改变父元素宽度以适应子元素,从而达到居中
.parent {
background-color: red;
width: fit-content;
margin: auto;
}
垂直居中
-
line-height
只适用于单行文本,令 line-height 与 height 相等
.parent {
height: 200px;
line-height: 200px;
background-color: red;
}
块级元素
水平居中
- margin: 0 auto;
.parent {
background-color: red;
}
.child {
width: 100px;
margin: 0 auto;
background-color: blue;
}
水平垂直居中
-
定位
知道子元素宽高的情况下
.parent {
position: relative;
height: 200px;
background-color: red;
}
.child {
width: 100px;
height: 100px;
position: absolute;
background-color: blue;
/* 法一 */
left: 50%;
top: 50%
margin-top: -50px;
margin-left: -50px;
/* 法二 */
/* calc() 可以混合使用各种单位来进行计算,如百分比、px、em、rem等单位都可以混在一起使用 */
left: calc(50% - 50px);
top: calc(50% - 50px);
}
-
定位 + transform
不知道子元素宽高的情况下
.parent {
position: relative;
height: 200px;
background-color: red;
}
.child {
width: 100px;
height: 100px;
position: absolute;
background-color: blue;
left: 50%;
top: 50%;
transform: translate(-50%, -50%)
}
- 定位 + margin
.parent {
position: relative;
height: 200px;
background-color: red;
}
.child {
width: 100px;
height: 100px;
position: absolute;
background-color: blue;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
- padding
.parent {
padding: 20px;
background-color: red;
}
.child {
height: 100px;
background-color: blue;
}
- flex
.parent {
height: 200px;
background-color: red;
dispaly: flex;
align-items: center;
justify-content: center;
}
.child {
width: 100px;
height: 100px;
background-color: blue;
}
- 伪元素
.parent {
height: 200px;
background-color: red;
text-align: center;
}
.child {
width: 100px;
height: 100px;
background-color: blue;
dispaly: inline-block;
/* vertical-align 设置行内元素的垂直对齐方式 */
vertical-align: middle;
}
.parent::before {
content: "";
width: 0;
height: 200px;
dispaly: inline-block;
vertical-align: middle;
}
-
calc()
给一个外边距直至铺满父元素,再利用 background-clip 裁剪
.parent {
height: 600px;
background-color: red;
dispaly: flex;
align-items: center;
justify-content: center;
}
.child {
width: 100px;
height: 100px;
padding: calc((100% - 100px) / 2);
/*
background-clip 规定背景的绘制区域
---------------------------------
border-box 背景被裁剪到边框盒
padding-box 背景被裁剪到内边距框
content-box 背景被裁剪到内容框
*/
background-clip: content-box;
background-color: blue;
}

浙公网安备 33010602011771号