一、CSS设置元素垂直居中
想要使元素在父容器中垂直居中,可以使用CSS的position和transform属性来实现。
首先,设置父容器为position: relative;,并将要居中的元素设置为position: absolute;。接着,使用transform对元素进行位移操作:top: 50%; transform: translateY(-50%);。
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
二、CSS元素垂直居中
如果要让一个单独的元素垂直居中,可以将其设置为display: flex;,并对其内容进行居中操作:
.parent{
display: flex;
justify-content: center; /*水平居中*/
align-items: center; /*垂直居中*/
}
三、CSS元素水平垂直居中
想要将元素水平和垂直同时居中,除了使用display: flex;之外,还可以使用CSS3的flexbox布局。
.parent{
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 200px;
height: 100px;
background-color: pink;
}
四、块级元素水平垂直居中的CSS代码
如果要让块级元素水平垂直居中,可以使用CSS的margin和calc()函数来实现。
.parent{
position: relative;
}
.child{
position: absolute;
top: calc(50% - 100px);
left: calc(50% - 50px);
width: 100px;
height: 200px;
margin: auto;
background-color: pink;
}
五、元素水平垂直居中怎么设置CSS
除了以上方法,还有一些其他的CSS技巧可以实现元素水平垂直居中:
display: table-cell;,设置父容器为display: table;,并在子元素中设置display: table-cell;可以使子元素水平和垂直居中。position: absolute;,通过设置top、left、bottom、right为0和设置margin: auto来使元素水平垂直居中。- 使用CSS3的
grid布局或者transform: translate(-50%, -50%);也可以实现元素的水平垂直居中。
原创文章,作者:UZZE,如若转载,请注明出处:https://www.506064.com/n/146410.html
微信扫一扫
支付宝扫一扫