Ishita Ishita - 1 month ago 17
CSS Question

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

I have a parent DIV with widht 100%;

Now, on the fly, it is populated with n number of children DIVs.

Now, I want to be able to caclulate and assign their width in CSS or LESS using calc method only (flex display doesnt work in my actual code which does not actually just deals with DIV s but actually svg elements using d3) so that their width is in this pattern

width of n-th child DIV = (100% / n) - 10

How can i achieve that?

Also, the DIV s need to be of alternative colors which i have managed to figure out how?

Any ideas how can I assign width on the fly using css or less?

http://jsfiddle.net/7r029v9n/2/ - here is the Jsfiddle

here is my code so far

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

Answer

Flexbox is perfect when you want to distribute the available space among children:

#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>

You can also use CSS tables:

#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>

Comments