This simple CSS code snippet helps you to change the background color on the hover event. It comes with a basic example of color boxes to demonstrate the change of color effect. Basically, the color boxes are arranged in an unordered list where the last list contains a class for background. It uses the CSS general sibling combinator (~) operator to select the element and hover pseudo-class to set a different background color. So, when you hover on a specific color, the background color is set accordingly.
How to Change Background Color On Hover
Basically, you can change the background color of an HTML element using the CSS hover pseudo-class and set a different color value. Let’s suppose you have a div element with a class name “bg”, then you can define the CSS rules as follows:
.bg { width: 400px; height: 400px; background: gray; } .bg:hover{ background: green; }
The HTML for the above CSS is as follows:
<div class="bg"></div>
In the above code example, a box has a gray background color. When you hover it, its background color will be changed to green. It’s a simple solution to change the background color. Now, let’s move to the demo page coding:
<ul class="menu"> <li><a href="#">h</a></li> <li><a href="#">g</a></li> <li><a href="#">i</a></li> <li><a href="#">p</a></li> <li><a href="#">l</a></li> <li class="bg"></li> </ul>
Style the boxes using the following CSS styles. These styles are optional, you can use the above code example.
* { margin: 0; padding: 0;} body { background:#e5e5e5;} .bg { position: fixed; z-index: -1; top: 0; right: 0; bottom: 0; left: 0; transition: .25s; pointer-events: none; } li { list-style:none; } li a { display:block; float:left; width:20%; padding:25px 0; text-align:center; font-family: 'HeydingsCommonIconsRegular', Helvetida Neue, sans-serif; font-weight:700; letter-spacing:1px; font-size:40px; color:#fff; background:#ccc; text-decoration:none; text-transform:uppercase; text-shadow:2px 2px 0 rgba(0,0,0,.25); transition:.25s;} li a:hover { margin:-10px 0 0 0; } .menu { width:500px; margin:60px auto 0 auto; border-radius:10px; overflow:hidden;} .menu li:first-child a { background:#ffca6d !important;} .menu li:nth-child(2) a { background:#ff6d6d !important;} .menu li:nth-child(3) a { background:#6dffb9 !important;} .menu li:nth-child(4) a { background:#6dcaff !important;} .menu li:nth-child(5) a { background:#ec6dff !important;} .menu li:first-child:hover ~ .bg { background: #ffca6d; } .menu li:nth-child(2):hover ~ .bg { background: #ff6d6d; } .menu li:nth-child(3):hover ~ .bg { background: #6dffb9; } .menu li:nth-child(4):hover ~ .bg { background: #6dcaff; } .menu li:nth-child(5):hover ~ .bg { background: #ec6dff; } .cd__main { display: flex; width: 100%; height:100vh; background:transparent !important;}
That’s all! hopefully, you have successfully changed the background color of an element on hover. If you have any questions or suggestions, feel free to comment below.