How to use the first-Child selector for a specific class

Asked

Viewed 118 times

7

Hello, I have several Ivs and some of them have a 'test' class, I would like the first-Hild selector to highlight only the first DIV that has the 'test' class, but it only works if the 'test' class is in the first div. From what I understand, the selector takes the first object of the type and not the class really. Anyone have any idea? In this example below, I wanted the div with "Test 2" to be highlighted by the selector (it is the first DIV that has the test class).

.teste:first-child{
	background-color:#F00;
	border:solid 4px #33CCCC;	
}
<div>
  Teste 1
</div>
<div class="teste">
  Teste 2
</div>
<div class="teste">
  Teste 3
</div>
<div class="teste">
  Teste 4
</div>

1 answer

6


There are no selectors that do this unfortunately, the current selectors work on the element tag and not on its class. Ideally here would be :first-of-class that doesn’t exist.

There’s a interesting idea that solves your problem. That’s using the selector ~.

In this case you apply the style to all classes, and then undo using the selector .classe ~ .classe, and thus delete the style in all but the first... The selector looks for an element with class x, preceded by another with class x.

Would that be:

div.teste {
    background-color: #F00;
    border: solid 4px #33CCCC;
    color: #ccf;
}

.teste ~ .teste {
    background-color: transparent;
    border: none;
    color: #000;
}
<div>
  Teste 1
</div>
<div class="teste">
  Teste 2
</div>
<div class="teste">
  Teste 3
</div>
<div class="teste">
  Teste 4
</div>

jsFiddle: https://jsfiddle.net/1fxcxgn4/


As I mentioned there is no immediate solution with CSS, although it is executable. If you want to use Javascript to avoid overloading CSS with rules that can be complex to remove you can use it like this:

var primeiroTeste = document.querySelector('.teste');
primeiroTeste.classList.add('classe');

where you would have in CSS:

.classe {
    background-color:#F00;
    border:solid 4px #33CCCC;   
}

jsFiddle: https://jsfiddle.net/1fxcxgn4/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.