L - 居中佈局

水平居中

先給出HTML結構佈局

<div class="par">
        <div class="child">我是子元素</div>
    </div>

方法1. 將子元素轉換爲行內元素

.par{
        text-align: center;
    }
    .child{
        background-color: tomato;
            
        display:inline-block;
    }

將子元素設置爲inline-block這樣既能夠像塊元素同樣設置盒模型,又能夠像行內元素同樣試用text-align:center進行居中flex

將子元素設置爲inline-block後,子元素爲塊級元素,寬度爲內容寬度code

方法2. 將子元素轉換爲table

.par{

    }
    .child{
        background-color: tomato;
            
        display:table;
        margin:0 auto;
    }

table元素是塊級元素,寬度自適應爲內容寬度,因此經過display:table對子元素進行轉換並設置塊元素居中標配margin:0 autoorm

方法3. 使用position+transform組合

.par{
        position: relative;
    }
    .child{
        background-color: tomato;
        width:300px;

        position: absolute;
        left:50%;
        transform: translateX(-50%);
    }

因爲子元素是個塊級元素(div),默認佔滿父元素寬度,因此咱們將子元素寬度設爲300pxit

原理很簡單,先用絕對定位將子元素置於距父元素左邊界一半的位置,而後再將子元素向左移動自身的一半,達到居中效果io

注意,position:relative將父元素設爲子元素絕對定位的參照物table

方法4. 利用flex佈局的justify-content

.par{
        display:flex;
        justify-content: center;
    }
    .child{
        background-color: tomato;
    }

因爲flex-grow屬性默認值爲0,flex-basis屬性默認值爲auto,因此寬度爲內容寬度(在沒有設置指定值時,不然爲指定值)form

順便說一句,flex很強大class

垂直居中

高度爲元素高度,就不指定具體值了原理

方法1. 父元素轉換爲table-ceil

.par{
        height:500px;

        display:table-cell;
        vertical-align:middle;
    }
    .child{
        background-color: tomato;
    }

子元素寬度爲內容寬度,父元素寬度爲子元素寬度

方法2. 利用position+transform組合

.par{
        height:500px;

        position: absolute;
    }
    .child{
        background-color: tomato;
        width:300px;
        
        position: absolute;
        top:50%;
        transform: translateY(-50%);
    }

不指定子元素寬度的話,子元素的內容將縱向展現

方法3. 使用flex佈局的align-items

.par{
        height:500px;

        display:flex;
        align-items:center;
    }
    .child{
        background-color: tomato;
        width:300px;
    }

水平垂直居中

上述兩種居中佈局的結合

方法1. 使用inline-block+text-align+table-cell+vertical-align

.par{
        width:500px;
        height:500px;
        border:1px solid #ccc;

        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    .child{
        background-color: tomato;
        width:300px;

        display:inline-block;
    }

方法2. 利用position+transform組合

.par{
        width:500px;
        height:500px;
        border:1px solid #ccc;

        position: relative;
    }
    .child{
        background-color: tomato;
        width:300px;

        position: absolute;
        left:50%;
        top:50%;
        transform: translate(-50%,-50%);
    }

方法3. 使用flex佈局

.par{
        width:500px;
        height:500px;
        border:1px solid #ccc;

        display:flex;
        justify-content: center;
        align-items: center;
    }
    .child{
        background-color: tomato;
        width:300px;
    }

有問題歡迎提問,實踐出真知

相關文章
相關標籤/搜索