Ivan Ivan - 3 months ago 5
CSS Question

Using JS to write CSS will cancel :hover properties defined in stylesheet

I have two divs. One is parent of the other. When I hover over the parent the child gets a different background color and font color. However when I run the function switch() that changes the inline style of the child element the hover propertie is canceled. In other words: after applying CSS with JS the child background doesn't change on hover.



document.querySelector('button').onclick = function() {
document.querySelector('.foo').style.backgroundColor = 'green';
}

.container {
background-color: lightgrey;
margin: auto;
width: 200px;
display: flex;
align-items: center;
height: 50px;
}
.foo {
width: 100px;
margin: auto;
text-align: center;
}
.container:hover > .foo {
background-color: #c01919;
color: yellow;
}

<div class="container">
<div class="foo">Hey there!</div>
</div>

<button>.foo(backgroundColor) -> green</button>





The real question is how to prevent inline style from canceling CSS :hover properties?

Is there a way to make the background color red on hover after the function has affected the inline style?

Answer

The real question is how to prevent inline style from canceling CSS :hover properties?

Short of using !important (which is awful, so don't), you can't. The point of inline style is that it is more specific that any selector.

Stop using inline style. Set the green colour in the stylesheet and then activate it by using JavaScript to change the classes that the element is a member of.

document.querySelector('button').onclick = function() {
  document.querySelector('.foo').classList.add('bar');
}
.container {
  background-color: lightgrey;
  margin: auto;
  width: 200px;
  display: flex;
  align-items: center;
  height: 50px;
}
.foo {
  width: 100px;
  margin: auto;
  text-align: center;
}
.bar {
  background-color: green; 
}
.container:hover > .foo {
  background-color: #c01919;
  color: yellow;
}
<div class="container">
  <div class="foo">Hey there!</div>
</div>

<button>.foo(backgroundColor) -> green</button>

Comments