Takzzg Guido
Takzzg Guido

Reputation: 73

Can't change color with a css class

Sorry if this is too basic, css confuses me.

So I have this "button":

<div class="col-md-12 bloque izq boton-tarjetas" onclick="mostrarTarjetas()">
    <p class="titulo2">- Tarjetas de Invitacion</p>
</div>

That button uses this css class:

.boton-tarjetas {
    cursor: pointer;
    background-color: #508365;
}

And when hovered over the button, the backgound-color property changes using this css class:

.boton-tarjetas:hover, .boton-activo {
    background-color: #30513d;
}

If the button es clicked, this js function triggers an accordion:

function mostrarTarjetas() {
    $('.contenido-tarjetas').slideToggle();
    $('.boton-tarjetas').toggleClass('boton-activo');
}

And that very same js function adds the boton-activo class to the button.

All that is working wonderfully, the problem is that the button should change color when hovered over (which is working) and when is clicked it should stay that color due to the added class on the js function.

If i check on the devtools, the boton-activo class is working, but it's being overwritten by the background-color property of the boton-tarjetas class.

Please help me.

Upvotes: 6

Views: 1029

Answers (2)

Danielprabhakaran N
Danielprabhakaran N

Reputation: 585

selector need to be more specific

HTML:

<div class="col-md-12 button-target">
<p class="title">accordian Title</p>
<div class="content-target">
There are many variations of passages of Lorem Ipsum available, but the  majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable.
</div>
</div>

CSS:

.button-target {
   cursor: pointer;
   background-color: #508365;
 } 
.button-target:hover, .button-target.button-active {
  background-color: #30513d;
 }

SCRIPT:

$('.button-target').click(function() {
   $('.content-target').slideToggle();
   $('.button-target').toggleClass('button-active');

});

https://jsfiddle.net/Danielprabhakaran_N/xpvt214o/581603/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

The issue is due to selector precedence. You need to make the .boton-activo class more specific so that it overrides any previous styles:

.boton-tarjetas {
  cursor: pointer;
  background-color: #508365;
}

.boton-tarjetas:hover, 
.boton-tarjetas.boton-activo { /* note additional class selector here */
  background-color: #30513d;
}

Note that the !important flag is another possible solution, but that should be avoided unless there is absolutely no alternative.

Upvotes: 7

Related Questions