Table layout example

by Matt Hinchliffe

HTML

<p class="demo-controls">
    <button id="remove">Remove a column</button>
    <button id="add">Add a column</button>
</p>

<div class="demo-canvas">
    <div class="wrapper"></div>
</div>

CSS

/* Demo housekeeping */
body {
  font: normal 16px/1.5 Arial, sans-serif;
}

.demo-controls {
  margin: 0 0 10px;
  text-align: center;
}

/* The meat */
.wrapper {
  display: table;
  margin: 0 auto;
  outline: 1px solid black;
}

.column {
  display: table-cell;
  width: 60px;
  height: 100px;
}

.column:nth-child(6n+1) {
  background: #F2777A;
}

.column:nth-child(6n+2) {
  background: #FC6;
}

.column:nth-child(6n+3) {
  background: #9C9;
}

.column:nth-child(6n+4) {
  background: #6CC;
}

.column:nth-child(6n+5) {
  background: #69C;
}

.column:nth-child(6n+6) {
  background: #C9C;
}

JavaScript

var wrapper = document.querySelector('.wrapper');
var remove = document.getElementById('remove');
var add = document.getElementById('add');
var columns = [];
var colours = 6;

add.onclick = function() {
    
    if (columns.length >= colours) {
        alert("Sorry, that's all the colours of the rainbow =)");
        return;
    }
    
    var col = document.createElement('div');
    col.className = 'column';
    wrapper.appendChild(col);
    columns.push(col);
};

remove.onclick = function() {
    if (columns.length <= 1) {
        alert("You'll have to add some more columns first!");
    }
    
    wrapper.removeChild(columns.pop());
};

add.click();