Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't change color with a css class

Tags:

jquery

css

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.

like image 251
Takzzg Guido Avatar asked Aug 09 '18 19:08

Takzzg Guido


People also ask

How do you add a color to a class in CSS?

Simply add the appropriate CSS selector and define the color property with the value you want. For example, say you want to change the color of all paragraphs on your site to navy. Then you'd add p {color: #000080; } to the head section of your HTML file.

Why is my CSS background not changing?

It's because both of your child elements are floated left. This means that the container won't stretch to the full height needed to contain the child elements.

Which property is used to change the color in CSS?

The background-color CSS property sets the background color of an element.


1 Answers

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.

like image 108
Rory McCrossan Avatar answered Oct 19 '22 06:10

Rory McCrossan