使用CSS或LESS根据同级计数(不固定)计算DIV的宽度

Calculate Width of a DIV based on sibling count (not-fixed) using CSS or LESS

本文关键字:计算 DIV LESS CSS 使用      更新时间:2023-09-26

我有一个宽度为100%的父div;

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

现在,我希望能够只使用calc方法在CSS或LESS中计算和分配它们的宽度(flex display在我的实际代码中不起作用,它实际上不仅处理DIV s,而且实际上使用d3处理svg元素),这样它们的宽度就成了这种模式

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

我怎样才能做到这一点?

此外,DIV需要具有替代颜色,我已经设法弄清楚了如何做到这一点?

有什么想法吗?我如何使用css或更少的css动态分配宽度?

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

这是我到目前为止的代码

.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);
}

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));
}
#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;  
}
<div id="parent"></div>

您也可以使用CSS表:

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

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));
}
#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;  
}
<div id="parent"></div>

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 */
}

但是,您将需要为您决定支持的任何数量的元素编写这样一个选择器,并且下一个选择器都将比上一个更长。