CSS 中幾種最常用的水平垂直居中的方法
點擊打開視頻講解更加詳細
一、使用 margin:auto
當元素有給定的高度以及寬度的時候,使用 margin: auto; 元素僅會水平居中,并不會進行垂直居中,
此時就需要設定元素的 position 為 absolute,父級元素的 position 為 relative,同時元素的上下左右都需要設定為 0,
<div >
<div ></div>
</div>
.box{
width: 200px;
height: 200px;
background-color: #eee;
position: relative;
margin-top: 20px;
}
.center1{
width: 50px;
height: 50px;
background-color: #00ACED;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
效果展示:
二、使用 position:absolute
當已經知道了要進行水平垂直居中的元素的寬高時,就可以通過設定 position: absolute 來實作,
但是,使用的同時還需要結合其他屬性才完整實作,
因為,單是設定 absolute,上左距離均為一半,就會出現下面這種情況,
很顯然可以看到,元素并不是完全居中,僅只有左上角的位置在中心點,
概念圖:

因此想要實作元素完全水平垂直居中,在設定了 absolute 定位后,可以設定 margin 值為負,或者使用 calc 來計算,上左距離在 50% 的基礎上還要減去元素本身一半的寬高,
margin 值為負或者 calc 計算均是在已知元素寬高的情況下,假設不知道元素的寬高,那么怎么實作水平垂直居中呢?這里就可以使用 transform 屬性,通過坐標位移來實作居中,
/* 結合 margin */
.center2{
width: 50px;
height: 50px;
background-color: #7FFFD4;
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
}
/* 結合 calc 計算*/
.center2{
width: 50px;
height: 50px;
background-color: #7FFFD4;
position: absolute;
left: calc(50% - 25px)
top: calc(50% - 25px);
}
/* 結合 transform */
.center2{
width: 50px;
height: 50px;
background-color: #7FFFD4;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
效果展示:

三、使用彈性布局
可以通過彈性布局來設定水平垂直居中,這里需要設定父級元素 display:flex; 還需要設定兩個屬性,
水平布局 justify-content 以及垂直布局 align-items,
<div >
<div ></div>
</div>
.box2{
background-color: #eee;
width: 200px;
height: 200px;
position: relative;
margin-top: 20px ;
display: flex;
justify-content: center;
align-items: center;
}
.center4{
width: 50px;
height: 50px;
background-color: #B39873;
}
效果展示:

四、文本水平對齊和行高
前面介紹的是元素如何實作水平垂直居中,下面介紹的是如何將文字進行水平垂直居中,
這第一個方法也是最經常用的,使用文本水平對齊 text-align 和行高 line-height 來實作的,
<div >
<div >文字居中</div>
</div>
.box3{
background-color: #eee;
width: 200px;
height: 200px;
margin-top: 20px;
}
.center5{
text-align: center;
line-height: 200px;
}
效果展示:

五、使用網格布局
第二個方法可以通過網格布局 grid 來實作,而這里通過 grid 有兩種方式實作,一種對元素本身屬性進行設定,另一種在元素的父級元素中設定,兩者看上去內容似乎差不多,不同的是在元素中設定的是 align-self 還要多了一個 margin,父級元素中是 align-items,
/* grid 元素中設定 */
.box4{
background-color: #eee;
width: 200px;
height: 200px;
margin-top: 20px;
display: grid;
}
.center6{
align-self: center;
justify-content: center;
margin: auto;
}
/* grid 父級元素中設定 */
.box5{
background-color: #eee;
width: 200px;
height: 200px;
margin-top: 20px;
display: grid;
align-items: center;
justify-content: center;
}
效果展示:

若對您有幫助,請點擊跳轉到B站一鍵三連哦!感謝支持!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/502745.html
標籤:其他
