我有一个随机数的子div。父div高度已知且已修复。我希望子div的高度为父div的高度除以子div的数量。 (在我的例子中有两个子div,但我不知道会有多少个div)
HTML
<div class="calendar-default">
<div class="calendar-plage" style="background-color: red;"> </div>
<div class="calendar-plage" style="background-color: green;"> </div>
</div>
CSS
.calendar-default{
background-color: black;
position: relative;
height: 100px;
width: 100px;
}
.calendar-plage{
height: auto; /* ??? */
}
小提琴最能解释我的问题:https://jsfiddle.net/z2anpsy7/
我设法用javascript做了但我只想用CSS做。有可能吗?
Ps:它在AngularJS应用程序中,如果你知道一个优雅的角度方式解决我的问题它也很棒!
答案 0 :(得分:4)
您可以使用flexbox和flex-direction: column;
.calendar-default {
background-color: black;
position: relative;
height: 100px;
display: flex;
flex-flow: column wrap;
}
.calendar-plage {
flex: 1 0 auto;
}
&#13;
<h2>2 children</h2>
<div class="calendar-default">
<div class="calendar-plage" style="background-color: red;"> </div>
<div class="calendar-plage" style="background-color: green;"> </div>
</div>
<h2>3 children</h2>
<div class="calendar-default">
<div class="calendar-plage" style="background-color: red;"> </div>
<div class="calendar-plage" style="background-color: green;"> </div>
<div class="calendar-plage" style="background-color: blue;"> </div>
</div>
&#13;
答案 1 :(得分:4)
为了横向传播孩子,我们使用display: table-cell
并垂直传播孩子,我们可以使用display: table-row
。但是display: table-row
需要一些内容,我通过伪元素提供,如下例所示。
尝试添加更多子项,它们会自动传播并适合父容器。
.parent {
height: 100px;
width: 100px;
display: table;
border: 1px solid black;
}
.child {
display: table-row;
width: 100px;
background-color: tomato;
}
.child:nth-child(2n) {
background-color: beige;
}
.child::after {
content:"";
}
答案 2 :(得分:1)
.calendar-default{
position: relative;
height: 100px;
width: 100px;
}
.calendar-plage{
height:50%
}
&#13;
<div class="calendar-default">
<div class="calendar-plage" style="background-color: red;"> </div>
<div class="calendar-plage" style="background-color: green;"> </div>
</div>
&#13;