2017-07-26 59 views
2

我有正確的div與動態高度和30%的寬度。 目標是讓紫色元素在右div上浮動,並在結束後留下剩餘空間。有沒有可能只用CSS做到這一點?拉伸div在浮動另一個div後

enter image description here

.container { 
 
     height: 500px; 
 
     width:100%; 
 
    } 
 
    
 
    .yellow { 
 
     width: 30%; 
 
     background: yellow; 
 
     float: right; 
 
     margin: 5px; 
 
    } 
 
    
 
    .purple { 
 
     background:purple; 
 
     height: 40px; 
 
     margin: 5px; 
 
     width:100%; 
 
     float:left; 
 
    }
<html> 
 
    <div class="container"> 
 
     <div class="yellow"> some content here <br/><br/><br/> some content here </div> 
 
    
 
     <div class="purple"> </div> 
 
     <div class="purple"> </div> 
 
     <div class="purple"> </div> 
 
     <div class="purple"> </div> 
 
    </div> 
 
    </html>

回答

4

如果你避免浮動紫色箱子,使他們block formatting contextsoverflow: hidden那麼你會得到你想要的結果。

基本上,浮動元素會導致它們彼此清除,因爲您在紫色框上將寬度設置爲100%。如果您將紫色框放在正常的文檔流中,並使用塊格式上下文來讓它們根據正確的浮動元素進行重新定形,您將得到結果。

.container { 
 
     height: 500px; 
 
     width:100%; 
 
    } 
 

 
    .yellow { 
 
     width: 30%; 
 
     background: lavender; 
 
     float: right; 
 
     margin: 5px; 
 
    } 
 

 
    .purple { 
 
     background: lightblue; 
 
     height: 40px; 
 
     margin: 5px; 
 
     overflow:hidden; 
 
    }
<div class="container"> 
 
    <div class="yellow"> some content here <br/><br/><br/> some content here </div> 
 

 
    <div class="purple"> </div> 
 
    <div class="purple"> </div> 
 
    <div class="purple"> </div> 
 
    <div class="purple"> </div> 
 
</div>

一些額外閱讀:https://www.sitepoint.com/understanding-block-formatting-contexts-in-css/