The visibility CSS property allows you to show or hide an element without affecting the layout of a document.
If you're looking to switch colors with buttons, here's a simple example that uses buttons to toggle the visibility of different color groups. The inline CSS has been reorganized for cleaner HTML and simpler JavaScript usage. You can find links to MDN documentation at the end of this answer.
// Cache the containers, and add a listener to the
// buttons container
const colors = document.querySelector('.colors');
const buttons = document.querySelector('.buttons');
buttons.addEventListener('click', handleClick);
// When a child in the buttons container is
// clicked (see event delegation below)...
function handleClick(e) {
// ...first check it's a button
if (e.target.matches('button')) {
// ... destructure its id from the dataset
const { id } = e.target.dataset;
// ... and use the id to toggle those elements
// in the colors container which have a `color` class
// and a class that matches the id
// (using a template string to create the selector)
colors
.querySelectorAll(`.color.${id}`)
.forEach(color => color.classList.toggle('hidden'));
}
}
.colors { display: flex; width: 60%; justify-content: left; align-items: center; }
.color { width: 20%; text-align: center; border: 2px solid white; }
.red { background-color: red; }
.blue { background-color: lightblue; }
.yellow { background-color: yellow; }
.green { background-color: lightgreen; }
.orange { background-color: orange; }
.pink { background-color: pink; }
.hidden { visibility: hidden; }
.buttons { margin-top: 1em; }
<div class="colors">
<div class="color group3 pink"><p>1</p></div>
<div class="color group1 blue"><p>2</p></div>
<div class="color group2 yellow"><p>3</p></div>
<div class="color group1 red"><p>4</p></div>
<div class="color group2 green"><p>5</p></div>
<div class="color group3 orange"><p>6</p></div>
</div>
<div class="buttons">
<button data-id="group1">Toggle group 1</button>
<button data-id="group2">Toggle group 2</button>
<button data-id="group3">Toggle group 3</button>
</div>
For more information, refer to the following resources: