Random Background Colors per Div

This project assigns random background colors to all <div> elements on the page using JavaScript, triggered on page load. Refreshing the page generates new colors, creating a dynamic visual effect. The layout uses CSS Flexbox to arrange three main divs (header, middle, bottom) in a column, with responsive adjustments for larger screens. While this could be used for playful UI elements or color-themed designs, it was primarily built for fun and to experiment with how div placement and ordering behave under various Flexbox properties, offering insights into CSS layout mechanics.
Project Overview
The core functionality is a simple script that iterates through all divs and sets random hex colors. Combined with Flexbox, it demonstrates layout flexibility. On refresh, colors change, highlighting how CSS affects visual structure.
Potential uses:
- Fun demos or interactive art.
- Educational tools for CSS learning.
- Themed interfaces with dynamic colors.
But it’s mostly an experiment in Flexbox effects, like order, flex-flow, and responsive wrapping.
Code Breakdown
The HTML structure is basic:
<div id="outer">
<div id="header">1 header (Refresh to change the colors)</div>
<div id="middle">2 middle</div>
<div id="bottom">3 bottom</div>
</div>
CSS uses Flexbox for layout:
#outer {
height: 100%;
display: flex;
flex-flow: column nowrap;
}
#header, #middle {
flex: 1 0 auto;
}
#bottom {
order: 1;
flex: 2 0 auto;
}
#middle {
order: 2;
}
This stacks divs vertically, with order reordering them (bottom first, then middle, header last visually).
Media query adjusts for larger screens:
@media (min-width: 768px) {
#outer {
flex-flow: column wrap;
}
#outer div {
flex: 1 0 50%;
order: 1;
}
}
JavaScript generates and applies colors:
function randomColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
function setDivColors() {
var elements = document.getElementsByTagName("div");
for (i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = randomColor();
}
}
setDivColors();
This runs on load, randomizing colors each refresh.
Studying CSS Effects
The project explores Flexbox’s impact on div placement:
flex-flow: Direction and wrapping.order: Visual reordering without DOM changes.- Responsive behavior with media queries.
It’s a hands-on way to see how properties like flex and order alter layouts, useful for learning CSS without complex apps.
Fun and Practical Aspects
Refreshing for new colors adds whimsy, but practically, it could inspire dynamic theming. This demo underscores how simple JS and CSS can create engaging experiments, emphasizing Flexbox’s power for modern layouts.