CSS之div嵌套問題及高度自適應問題的五種實現--我的總結

如下是在本身實習生面試的時候遇到的一個問題,過後本身也去總結了一下。
問題描述以下:
一個外層div裏面嵌套兩個內部div,外層div高度固定(假設未知),內層上面的div高度固定,如何讓下面的div實現撐滿外層的div高度?
看到過網上有相似的問題,可是大部分都是假設外層高度爲100%或者是已知的,而我遇到的是外層高度雖然固定,可是咱們並不知道是多少(這裏須要說明一下,代碼中外層的高度我雖然本身給了固定值,可是隻是爲了效果,後面其實都沒有用到這個值,基本就知足咱們不知道外層的具體高度是多少這個條件了),因此也參看了網上的一些零散的解法,本身也都去實踐了一下,最後總結出五種能夠實現的方法。
HTML代碼以下:面試

<div class="wrapper">
    <div class="div1">888888888</div>
    <div class="div2">12321423512</div>
</div>

五種實現方法以下:
一、使用flex佈局實現
app

.wrapper {
    width: 200px;
    height: 400px;
    margin: 100px auto; /*這裏的margin純屬爲了測試時候的顯示效果居中,無實際用途*/
    background: aquamarine;
    display: flex;
    flex-direction: column;
}

.div1 {
    height: 100px;
    width: 100%;
    background-color: violet;
    order: 0;
}

.div2 {
    background-color: teal;
    width: 100%;
    order: 1;
    flex-grow: 1;
}

二、下面的div使用position:absolute + top/bottom實現
佈局

.wrapper {
    width: 200px;
    height: 400px;
    margin: 100px auto;
    background: aquamarine;
    position: relative;
}
  
.div1 {
    height: 100px;
    background-color: violet;
}

.div2 {
    background-color: teal;
    width: 100%;
    position: absolute;
    top: 100px;
    bottom: 0;
}

三、下面的div設置margin-top爲負值實現
測試

.wrapper {
    width: 200px;
    height: 400px;
    margin: 100px auto;
    background: aquamarine;
    position: relative;
}
  
.div1 {
    height: 100px;
    background-color: violet;
    position: relative;
}

.div2 {
    background-color: teal;
    width: 100%;
    height: 100%;
    margin-top: -100px;
    box-sizing: border-box;
    padding-top: 100px;
}

四、外層div設置padding-top,內層上面的div絕對定位實現
flex

.wrapper {
    width: 200px;
    height: 400px;
    margin: 100px auto;
    box-sizing: border-box;
    padding-top: 100px;
    background: aquamarine;
    position: relative;
}

.div1 {
    height: 100px;
    width: 100%;
    background-color: violet;
    position: absolute;
    top: 0;
}

.div2 {
    background-color: teal;
    width: 100%;
    height: 100%;
}

五、上面的div絕對定位,top:0;下面的div設置box-sizing + padding-topcode

.wrapper {
    width: 200px;
    height: 400px;
    margin: 100px auto;
    background: aquamarine;
    position: relative;
}

.div1 {
    height: 100px;
    width: 100%;
    background-color: violet;
    position: absolute;
    top: 0;
}

.div2 {
    background-color: teal;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding-top: 100px;
}

第一次寫文章,有什麼問題歡迎指出,你們有什麼其餘的實現方法也歡迎一塊兒分享~~it

相關文章
相關標籤/搜索