2014-11-24 74 views
1

如果兩個div彼此相鄰,如果一個設置了寬度,另一個應該自動用盡剩餘空間,如何對齊兩個div。如果在幫助中省略了設置的寬度div,則其他div應調整大小以佔用容器div中的所有空間。CSS並排對齊2個div

它被用於圖像/內容設計。我想要它,所以如果沒有圖像,內容佔用它的空間。

這裏是我的代碼:

CSS

.sub-row-wrapper { 
    background: #f00; 
    text-align: left; 
    width: auto; 
    position:relative; 
    padding: 12px; 
    margin-bottom: 12px; 
    border-bottom: 1px; 
    border-style: solid; 
    border-color: #ccc; 
} 

.sub-row-left-col { 
    background: #ff0; 
    display:inline-block; 
    width: 25%; 
    text-align: left; 
} 

.sub-row-right-col { 
    background: #f0f; 
    display:inline-block; 
    width: auto; 
} 

HTML

<div class="sub-row-wrapper"> 

    <div class="sub-row-left-col"> 
     <p>Left img</p> 
    </div> 

    <div class="sub-row-right-col"> 
     <p>This should be positioned right of 'left img' and should not go underneath the left img</p> 
    </div> 
</div> 

我有以下代碼

http://jsfiddle.net/fr9zvaj3/

什t我想在第一個div上是黃色方塊坐在紫色方塊的左邊。黃色的盒子應該寬25%,紫色的盒子應該用完剩下的空間。

當我刪除的黃色框,紫框應自動進入全寬(因爲它在第2行)

回答

2

一種解決方案是使用display: flex到容器,並設置width: 100%到紫色的div:

.sub-row-wrapper { 
 
    background: #f00; 
 
    text-align: left; 
 
    width: auto; 
 
    position: relative; 
 
    padding: 12px; 
 
    margin-bottom: 12px; 
 
    border-bottom: 1px; 
 
    border-style: solid; 
 
    border-color: #ccc; 
 
    display: flex;/*set display to flex*/ 
 
} 
 
.sub-row-left-col { 
 
    background: #ff0; 
 
    display: inline-block; 
 
    width: 25%; 
 
    text-align: left; 
 
} 
 
.sub-row-right-col { 
 
    background: #f0f; 
 
    display: inline-block; 
 
    width: 100%;/*set width to 100%*/ 
 
}
<body> 
 

 
    <div class="sub-row-wrapper"> 
 

 
    <div class="sub-row-left-col"> 
 
     <p>Left img</p> 
 
    </div> 
 

 
    <div class="sub-row-right-col"> 
 
     <div class="post-content"> 
 
     <p>This should be positioned right of 'left img' and should not go underneath the left img</p> 
 
     </div> 
 
    </div> 
 

 
    </div> 
 

 
    <div class="sub-row-wrapper"> 
 

 
    <div class="sub-row-right-col"> 
 
     <div class="post-content"> 
 
     <p>This should be full width when I put enough content in to make it full width</p> 
 
     </div> 
 
    </div> 
 

 
    </div> 
 

 
</body>

參考

flex

0
.sub-row-left-col { 
    background: #ff0; 
    display:inline-block; 
    width: 25%; 
    text-align: left; 
    float: left; 
} 

.sub-row-right-col { 
    background: #f0f; 
    display:inline-block; 
    width: 100%; 
} 

應該做的伎倆,我相信。 float: left;width:100%