![](/img/trans.png)
[英]Is it possible to rearrange the divs inside a container according to number of divs inside?
[英]Fit any number of divs inside a container?
我有一個更大的div與子元素如波紋管:
<div class=bigger>
<div>A</div>
<div>B</div>
<div>C</div>
</div>
如果我有一個像這樣的CSS:
.bigger
{
heigh: 300px;
}
那么它的所有孩子都需要100px
的高度,即每個孩子獲得相同的高度。
即使孩子的數量增加或減少,我的意思是:
<div class="bigger">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
</div>
所有的孩子div應該得到相同的高度,它應該是更大的高度/不。 兒童div。
這有什么CSS解決方案嗎? 我不想使用javaScript
如果你想在純CSS中實現這一點,你可以試試這個
我已經設置了4個項目。 您可以將其擴展到您想要的任意數量的項目。
/* one item */
.bigger > div:first-child:nth-last-child(1) {
height: 300px;
}
/* two items */
.bigger > div:first-child:nth-last-child(2),
.bigger > div:first-child:nth-last-child(2) ~ div {
height: 150px;
}
/* three items */
.bigger > div:first-child:nth-last-child(3),
.bigger > div:first-child:nth-last-child(3) ~ div {
height: 100px;
}
/* four items */
.bigger > div:first-child:nth-last-child(4),
.bigger > div:first-child:nth-last-child(4) ~ div {
height: 75px;
}
使用Flexbox的解決方案:
.bigger {
height: 400px;
background: #eea;
display: flex;
flex-direction: column;
}
.bigger div {
margin: 4px;
border: 1px dotted green;
flex: auto;
}
演示: http ://codepen.io/anon/pen/nAjLt(注意Codepen的供應商前綴)
.bigger {
width:100%;
height:auto;
border:1px solid red;
}
.bigger div {
height:100px;
width:100%;
border:1px solid blue;
}
使用此css,為您的目的,通過將height
設置為auto
it will adjust to any no of divs
。
另外.bigger div
會將所有.bigger div
設置為100px高度。
編輯:固定容器
.bigger {
width:100%;
height:300px;
border:1px solid red;
display:table;
}
.bigger div {
display:table-row;
height:auto;
width:100%;
}
對所有瀏覽器也一樣:)
允許元素占用相等的空間是傳統上只有使用<table>
s才能實現的。 但是,您可以使用CSS來使<div>
的行為類似於<table>
:
HTML
<div class=bigger>
<div>A</div>
<div>B</div>
<div>C</div>
<div>A</div>
<div>B</div>
<div>C</div>
<!-- add or remove any number of <div>s here -->
</div>
(相關)CSS
.bigger {
display: table;
height: 300px;
width: 100%;
}
.bigger > div {
display: table-row;
border-top: 1px solid black;
border-bottom: 1px solid black;
}
要與孩子和父母一起工作,您需要使用auto
和max
<div class="bigger">
<div>A</div>
<div>B</div>
<div>C</div>
</div>
在這里你可以使用
.bigger {
height: auto; // this will do the trick..
overflow: none;
min-height: 300px;
}
使用max和min,只是為了確保每次孩子增加或減少時height
保持不變,然后使用:
.bigger div {
height: 100%; // note this..
}
試試這個小提琴: http : //jsfiddle.net/afzaal_ahmad_zeeshan/2bJfW/再添加一個div並檢查一下,
如果你想動態創建div高度,那么沒有CSS,你需要JS或者讓我們說jQuery。 因為你需要計算孩子的數量,然后改變他們的身高百分比,讓我們說從100
到30
(對於3)或22
對於(4)等等,因為文本將不適合那個大小。
.bigger
{
height: auto;
}
.bigger div
{
height:50px;
}
你應該提到每個內部div的高度,然后才能正常工作。
現在你在更大的div里面添加另一個內部div元素,高度應該相同。
在這里我提到了高度50px,你給出了你想要的高度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.