溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

CSS如何實現(xiàn)子元素div水平垂直居中

發(fā)布時間:2021-03-17 11:09:17 來源:億速云 閱讀:203 作者:清風 欄目:web開發(fā)

本文將為大家詳細介紹“CSS如何實現(xiàn)子元素div水平垂直居中”,內(nèi)容步驟清晰詳細,細節(jié)處理妥當,而小編每天都會更新不同的知識點,希望這篇“CSS如何實現(xiàn)子元素div水平垂直居中”能夠給你意想不到的收獲,請大家跟著小編的思路慢慢深入,具體內(nèi)容如下,一起去收獲新知識吧。

div基本布局

<div class="main">
   <div class="center"></div>
  </div>

css樣式

1. 配合定位與margin:auto

父元素加相對定位,子元素加絕對定位

 .main{
    width: 300px;
    height: 300px;
    background-color: red;
    position: relative;
   }
   .center{
    width: 100px;
    height: 100px;
    background-color: skyblue;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
   }

2.利用flex布局,設置水平與豎直方向的內(nèi)容居中。

 .main{
    width: 300px;
    height: 300px;
    background-color: red;
    display: flex;
    justify-content: center;
    align-items: center;
   }
   .center{
    width: 100px;
    height: 100px;
    background-color: greenyellow;
   }

3.利用position:absolute與transform

:這里需要記住的是transform中translate使用百分比時相對的是自己的長寬,不是父盒子的。

 .main{
     width: 300px;
     height: 300px;
     background-color: red;
     position: relative;
    }
    .center{
     width: 100px;
     height: 100px;
     background-color: pink;
     position: absolute;
     left: 50%;
     top: 50%;
     transform: translateX(-50%) translateY(-50%);
    }

4.定位 與負margin配合

只適合子盒子長寬固定的情況

 .main{
     width: 300px;
     height: 300px;
     background-color: red;
     position: relative;
    }
    .center{
     width: 100px;
     height: 100px;
     background-color: pink;
     position: absolute;
     left: 50%;
     top: 50%;
     margin-left: -50px;
     margin-top: -50px;
    }

5.display:table-cell

display:table-cell;與vertical-align:middle 的作用是讓子盒子在數(shù)值方向上居中

margin:auto;則讓子盒子在水平方向居中,若只想讓盒子在某個方向居中,去掉另一個就可以了。

.main{
     width: 300px;
     height: 300px;
     background-color: red;
     display: table-cell;
     vertical-align: middle;
    }
    .center{
     width: 100px;
     height: 100px;
     background-color: #000;
     margin: auto;
    }

如果你能讀到這里,小編希望你對“CSS如何實現(xiàn)子元素div水平垂直居中”這一關鍵問題有了從實踐層面最深刻的體會,具體使用情況還需要大家自己動手實踐使用過才能領會,如果想閱讀更多相關內(nèi)容的文章,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI