2017-04-09 131 views
1

如何顯示不同數量的div?例如,第一部分有三個div,第二部分有兩個。等寬div取決於寬度?

但它們需要是相同的寬度 - 所以div總是填充該部分,無論有多少個div。

DIV - DIV - DIV
DIV --------- DIV

我想我需要使用最大寬度?是對的嗎?

section { 
 
    width: 960px; 
 
    background: grey; 
 
} 
 

 
div { 
 
    display: inline-block; 
 
    margin: 0; 
 
    height: 200px; 
 
    background: black; 
 
    width: 33%; 
 
}
<section> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
</section> 
 

 
<section> 
 
<div></div> 
 
<div></div> 
 
</section>

+0

你試過最大寬度嗎?不清楚你問什麼,無論行上有多少div,填滿所有相同寬度或所有行的div? –

+0

@GCyrillus對不起 - 是所有的行填充 – James

+1

所以roberto和mickael回答你,flex將通過柔性如果包裹設置和最小寬度來調整每行最大div的最大數量從一個單節完美管理這:) –

回答

2

section { 
 
    width: 960px; 
 
    background: grey; 
 
display: flex; 
 
} 
 

 
div { 
 
    display: inline-block; 
 
    height: 200px; 
 
    background: black; 
 
flex: 1 1 auto; 
 
margin: 0 1rem; 
 
}
<section> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
</section> 
 

 
<section> 
 
<div></div> 
 
<div></div> 
 
</section>

2

您可以在父用display: table,並display: table-cell的孩子。

section { 
 
    display: table; 
 
    margin: 0 0 1em; 
 
    width: 100%; 
 
} 
 
section > div { 
 
    display: table-cell; 
 
    background: #eee; 
 
    border: 1px solid #aaa; 
 
    height: 1em; 
 
}
<section> 
 
    <div></div> 
 
    <div></div> 
 
    <div></div> 
 
</section> 
 

 
<section> 
 
    <div></div> 
 
    <div></div> 
 
</section>

1

撓曲會如果包裹被設置和最小寬度到的div調MAX數在每個行完全由單一部分經由柔性管理此

section { 
 
    width: 960px; 
 
    background: grey; 
 
    display:flex; 
 
    flex-wrap:wrap; 
 
    justify-content:space-between; 
 
    padding:3px;/* equals, to fit children margins value */ 
 
} 
 

 
div { 
 
    display: inline-block; 
 
    margin:3px ; 
 
    height: 200px;/* can be be min-height or removed to let tallest div to set row's height */ 
 
    background: black; 
 
    min-width: 32%; 
 
    flex:1; 
 
} 
 
.ha div { 
 
height : auto; 
 
color:white; 
 
padding:1em; 
 
}
<section> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
</section> 
 
<hr/> 
 
<section> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
<div></div> 
 
</section> 
 
<hr/> 
 
<section class="ha"> 
 
<div> hi <i>(let's height be)</i></div> 
 
<div> the<br/>world</div> 
 
</section>