2016-02-13 47 views
0

我一直在廣泛閱讀這方面的內容,但一直沒有能夠解決它到我滿意。同樣分佈在一個div內的3個div - 沒有浮動

我有一個div(<section>),其中包含一個<p>和3 <div> s。我想在一行中平均分配3個div,以便第一個div的左邊界位於文檔的左邊界(<body>)和文檔右邊界的第三個div的右邊界。

我不想使用浮動,因爲背景色會消失。

我試過flex但justify-content沒有產生預期的結果。

這是JSBIN上的代碼。

謝謝!

+0

裹的div和彎曲的包裝。 –

+0

可能重複[如何對齊3個div(左/中/右)在另一個div?](http://stackoverflow.com/questions/2603700/how-to-align-3-divs-left-center-right -inside-another-div) –

+0

謝謝Michael_B,我那篇文章有鏈接http://stackoverflow.com/questions/2603700/how-to-align-3-divs-left-center-right-inside-another- div/32122011#32122011它解釋瞭如何做到這一點,爲什麼'flex'是最有效的解決方案。 –

回答

0

您可以在容器上使用display: flex,並將三個div元素的寬度設置爲其容器的三分之一(或儘可能接近)。容器必須具有設定的寬度(像素或百分比)才能工作。

#container { 
 
    display: flex; 
 
    height: 600px; 
 
    width: 600px; 
 
    background-color: lightgreen; 
 
} 
 
#container div { 
 
    border: 1px solid black; 
 
    margin: 0 10px; 
 
    width: 33.333333%; 
 
} 
 
#container div img { 
 
    width: 100%; 
 
}
<div id="container"> 
 
    <div id="content1"> 
 
    I'm some content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing. 
 
    <img src="http://i.imgur.com/P8z2H80.jpg"> 
 
    </div> 
 
    <div id="content2"> 
 
    I'm some more content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing. 
 
    <img src="http://i.imgur.com/NfnBZAI.jpg"> 
 
    </div> 
 
    <div id="content3"> 
 
    I'm even more content. Regardless of the width of this div, the content will move to the next line and stay within the div instead of overflowing. 
 
    <img src="http://i.imgur.com/W8M37N2.jpg"> 
 
    </div> 
 
</div>