2016-08-03 99 views
1

我正努力將兩個div對齊到父母的底部。將兩個重疊的div對齊到父母的底部

  • 白色(class="section")是父div,它是100%寬;
  • 灰色(class="text")是100%寬,可以有隨機高度取決於內容,它可以有更小的高度比白色和橙色,其底部必須與白色底部對齊;
  • 橙色(class="icon")具有固定的寬度和高度,其底部必須與白色底部對齊並且應該向右拉(可能與右側有一些偏移),白色的高度必須適應不適合不到橙色的高度。

我試過的vertical-align: bottomposition: absolutefloat但無濟於事不同的組合。

的jsfiddle:https://jsfiddle.net/ca9we2jo/

我希望它是什麼樣子:

Layout

回答

2

您可以使用CSS flex如下實現它:

body { 
 
    background-color: #333333; 
 
    margin: 0; 
 
} 
 
.container { 
 
    margin: 0 auto; 
 
    width: 80%; 
 
} 
 
.section { 
 
    background-color: #FFFFFF; 
 
    min-height: 200px; 
 
    margin-bottom: 100px; 
 
    flex-direction: column-reverse; 
 
    position: relative; 
 
    display: flex; 
 
    width: 100%; 
 
} 
 
.text { 
 
    background-color: #999999; 
 
    padding-right: 270px; 
 
    height: 150px; 
 
} 
 
.tall { 
 
    height: 300px; 
 
} 
 
.icon { 
 
    width: 250px; 
 
    height: 250px; 
 
    background-color: #FF9933; 
 
    border: #000000 2px dashed; 
 
    z-index: 1; 
 
    position: absolute; 
 
    bottom: 0; 
 
    right: 0; 
 
}
<div class="container"> 
 
    <div class="section"> 
 
    <div class="text"> 
 
     <b>Case 1:</b> 
 
     Gray has lower height than orange 
 
    </div> 
 
    <div class="icon"> 
 
    </div> 
 
    </div> 
 
    <div class="section"> 
 
    <div class="text tall"> 
 
     <b>Case 2:</b> 
 
     Gray has bigger height than orange 
 
    </div> 
 
    <div class="icon"> 
 
    </div> 
 
    </div> 
 
</div>

+0

謝謝,它的工作原理。除了我從'.text'中刪除'padding-right:270px;',因爲我需要將其中的內容居中。 – Taosique

+0

@Taosique好的,它可以滿足你的需要,歡迎你的光臨) –

0

您需要確保在設置div .icon的位置時,爲其父div聲明一個位置。當爲元素設置位置值時,它將計算它相對於聲明位置的下一個直接父div的位置。如果.section沒有設置位置,那麼.icon會計算它相對於.container的位置(如果容器已設置位置)。

<div class="container"> 
    <div class="section"> 
    <div class="text"> 
     <b>Case 1:</b> 
     Gray has lower height than orange 
    </div> 
    <div class="icon"> 
    </div> 
    </div> 
    <div class="section"> 
    <div class="text tall"> 
     <b>Case 2:</b> 
     Gray has bigger height than orange 
    </div> 
    <div class="icon"> 
    </div> 
    </div> 
</div> 



body { 
    background-color: #333333; 
    margin: 0; 
} 
.container { 
    margin: 0 auto; 
    width: 80%; 
} 
.section { 
    position:relative; 
    background-color: #FFFFFF; 
    min-height: 200px; 
    margin-bottom: 200px; 
    width: 100%; 
} 
.text { 
    background-color: #999999; 
    height: 100px; 
    width: 100%; 
    text-align: right; 
    position:absolute; 
    left:0; 
    bottom:0; 
} 
.tall { 
    height: 300px; 
} 
.icon { 
    width: 250px; 
    height: 250px; 
    background-color: #FF9933; 
    border: #000000 2px dashed; 
    z-index: 1; 
    position: absolute; 
    right:0; 
    bottom:0; 
}