一、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/zh-tw/n/146410.html
微信掃一掃
支付寶掃一掃