使用CSS或LESS基于兄弟计数(未固定)计算DIV的宽度

时间:2014-09-15 20:36:56

标签: javascript html css d3.js less

我有100%的父DIV;

现在,它在运行中填充了n个子DIV。

现在,我希望能够使用计算方法在CSS或LESS中进行caclulate并分配宽度(flex显示在我的实际代码中不起作用,实际上并不只是处理DIV但实际上是使用d3的svg元素)所以他们的宽度是这种模式

第n个孩子的宽度DIV =(100%/ n) - 10

我如何实现这一目标?

此外,DIV需要有其他颜色,我已设法弄清楚如何?

任何想法如何使用css或更少的动态分配宽度?

http://jsfiddle.net/7r029v9n/2/ - 这是Jsfiddle

这是我到目前为止的代码

.parent {
    width: 100%;
    height: 50%;
    background: pink;
    border: 1px solid red;
    min-width: 400px;
    min-height: 200px;
}

.child {
    min-height: 200px;
    min-width: 10px;
    border: 1px solid black;   
    display: inline-block;
}

.child:nth-child(even) {
    background: blue; 
    width: calc(100%/n -10);
}

.child:nth-child(odd) {
    background: green;  
    width: calc(100%/n -10);
}

2 个答案:

答案 0 :(得分:8)

当您想要在儿童中分配可用空间时,Flexbox是完美的:

#parent {
  display: flex;
}
.child {
  flex-grow: 1;
  margin: 5px;
}



var parent = document.getElementById('parent');
var child = document.createElement('div');
child.className = 'child';
var n = Math.round(Math.random() * 10);
for (var i = 0; i < n; ++i) {
  parent.appendChild(child.cloneNode(false));
}
&#13;
#parent {
  display: flex;
  min-width: 400px;
  min-height: 200px;
  background: pink;
  border: 1px solid red;
}
.child {
  min-height: 200px;
  min-width: 10px;
  border: 1px solid black;   
  display: inline-block;
  flex-grow: 1;
  margin: 5px;
}
.child:nth-child(even) {
  background: blue; 
}
.child:nth-child(odd) {
  background: green;  
}
&#13;
<div id="parent"></div>
&#13;
&#13;
&#13;

您也可以使用CSS表格:

#parent {
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
}
.child {
  display: table-cell;
}

&#13;
&#13;
var parent = document.getElementById('parent');
var child = document.createElement('div');
child.className = 'child';
var n = Math.round(Math.random() * 10);
for (var i = 0; i < n; ++i) {
  parent.appendChild(child.cloneNode(false));
}
&#13;
#parent {
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
  min-width: 400px;
  height: 200px;
  background: pink;
  border: 1px solid red;
}
.child {
  display: table-cell;
  height: 200px;
  width: 10px;
  border: 1px solid black;
}
.child:nth-child(even) {
  background: blue; 
}
.child:nth-child(odd) {
  background: green;  
}
&#13;
<div id="parent"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

AFAIK,了解当前CSS中兄弟姐妹数量的唯一方法是组合使用:nth-child:nth-last-child,例如

div:nth-child(1):nth-last-child(3),
div:nth-child(2):nth-last-child(2),
div:nth-child(3):nth-last-child(1) {
   width: 33.3%; /* if there are 3 divs, make them 1/3 of the container width */
}

但是你需要为你决定支持的任何元素编写这样的选择器,并且每个下一个选择器都会比前一个更长。