Just like we can use unsplash image source to use random images. Likewise, can we achieve background color using just css? If yes can anyone tell how to do it?
I use a random function to generate a random color for the background in the style. But it doesn't give any output
P粉8785105512023-09-07 19:53:12
This will require at least some JS to randomly generate colors
const container = document.getElementById('element'); generateRandomColor(); function generateRandomColor() { // 16777215 is decimal equivalent of FFFFFF in hexadecimal const randomHex = Math.floor(Math.random() * 16777215).toString(16); container.style.backgroundColor = `#${randomHex}`; container.innerHTML = `#${randomHex}`; }
.container { height: 100px; width: 100%; border: 1px solid black; margin-bottom: 5px; color: #fff; display: flex; justify-content: center; align-items: center; font-weight: bold; font-size: 24px; }
<div id="element" class="container"></div> <button onclick="generateRandomColor()">Generate Random Color</button>