Apply color to font in element clicked only with CSS

6

I have the following HTML:

<div class="trabalheSubEsqTitulo">Fale Conosco</div>

When I click on the div trabalheSubEsqTitulo , I want it to apply color:red , however, I only want this with CSS.

Can you do it?

    
asked by anonymous 17.11.2014 / 17:16

4 answers

9

With div I'm not sure if it's possible, but with an anchor you can use the pseudo- class :target , like this:

.trabalheSubEsqTitulo:visited { color: blue; }
.trabalheSubEsqTitulo:target { color: red; }
<a id="nome-unico" href="#nome-unico" class="trabalheSubEsqTitulo">teste 1</a>
<a id="outro-nome-unico" href="#outro-nome-unico" class="trabalheSubEsqTitulo">teste 2</a>

The identifier in href must be unique, and match the id of each item. The :visited rule is to keep the blue on the links already clicked. Beware that this rule must come before the other in the CSS.

:target works like this: If the current URL of the document has a hash ( #qualquer-coisa ) equal to the ID of an element, that element is :target . In our example, clicking each link defines the hash of the document as the ID of that link. It is then selected by :target declared in CSS.

    
17.11.2014 / 17:25
4

You can do this using the pseudo-selector :active , but the only while pressing / holding the mouse. To keep the class I think even just with JavaScript.

.trabalheSubEsqTitulo:active {
    color:red
}
<div class="trabalheSubEsqTitulo">Fale Conosco</div>

There is another way that is to use a checkbox as a flag ... Adding a label with the for="check" attribute (which points to the checkbox ID) and hiding the checkbox, we can do like this:

input[type="checkbox"] {
    display: none;
}
input[type="checkbox"]:checked + label {
    color: red;
}
<input type="checkbox" id="check" />
<label for="check" class="trabalheSubEsqTitulo">Fale Conosco</label>
    
17.11.2014 / 17:22
2

Another way would be to use the tabindex attribute, for example:

.trabalheSubEsqTitulo:focus {
  color: red;
  outline: none;
}
<div class="trabalheSubEsqTitulo" tabindex="0">Fale Conosco</div>

The bad side of this solution is that it works with the focus state, ie if you change the focus to any other element, your focus will be red.

For a bullet-proof and 100% efficient solution, JavaScript is still required.

    
17.11.2014 / 19:20
1

I do not know how to keep color just with CSS after clicking, but to keep the color after the click should be a link and the selector would be :visited

To set the color when you click it would look like this:

.trabalheSubEsqTitulo:active {
    color:red;
}

Fiddle Demonstration:

.trabalheSubEsqTitulo:active {
    color:red;
}
<div class="trabalheSubEsqTitulo">Fale Conosco</div>
    
17.11.2014 / 17:24