I'll get straight to the point.
I have 4 elements (background-1, background-2, background-3, background-4).
When I first arrive on the page I want Background-1 to have "background-color: #D8D7D8;" and the three others "background-color: #FBFBFB;". Then whenever I hover another background-x I want all of them to be #FBFBFB except the one being hovered which would be in #D8D7D8.
I know this probably pretty easy for you, but not for me haha.
My css looks like this :
.background-1 :hover{
background: #D8D7D8;
transition: .3s ease-in-out;
}
.background-2 :hover{
background: #D8D7D8;
transition: .3s ease-in-out;
}
.background-3 :hover{
background: #D8D7D8;
transition: .3s ease-in-out;
}
.background-4 :hover{
background: #D8D7D8;
transition: .3s ease-in-out;
}
Here is how it looks like : Imgur
Thank you in advance !
Milack
CodePudding user response:
Assuming all four elements are siblings, you could do something like below.
For the default bg1
value, I've suggested a JavaScript event handler.
const divs = document.querySelectorAll('.bg');
function clearBgExcept(target) {
divs.forEach(div => div.style.backgroundColor = div !== target ? "#FBFBFB" : "#D8D7D8");
}
function clearAllBg() {
divs.forEach(div => div.style.backgroundColor = div.dataset.default ? "#D8D7D8" : "#F8F8F8" );
}
divs.forEach(el => el.addEventListener('mouseover', e => {
clearBgExcept(e.target);
}));
divs.forEach(el => el.addEventListener('mouseout', () => {
clearAllBg();
}));
.wrapper {
min-width: 300px;
min-height: 300px;
margin: 0 auto;
display: grid;
grid-gap: 10px;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
}
.bg {
background-color: #FBFBFB;
border: 1px solid #CCC;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: .3s ease-in-out;
}
.bg[data-default="true"], .bg:hover {
background-color: #D8D7D8;
}
<div >
<div data-default="true">BG1</div>
<div >BG2</div>
<div >BG3</div>
<div >BG4</div>
</div>
CodePudding user response:
Assuming that your elements are siblings, then there's no need for Javascript:
.background-1,
.background-2,
.background-3,
.background-4 {
background-color: #FBFBFB;
padding: 2em;
}
.background-1 {
background-color: #D8D7D8;
}
.background-1:hover {
background: #D8D7D8;
transition: .3s ease-in-out;
}
.background-2:hover {
background: #D8D7D8;
transition: .3s ease-in-out;
}
.background-3:hover {
background: #D8D7D8;
transition: .3s ease-in-out;
}
.background-4:hover {
background: #D8D7D8;
transition: .3s ease-in-out;
}
.column:hover .background-1:not(:hover) {
background-color: #FBFBFB;
}
<div >
<div >
B1
</div>
<div >
B2
</div>
<div >
B3
</div>
<div >
B4
</div>
</div>
The only "clever" part is to reset the background-1
colour when the parent element is hovered but background-1
is not hovered.