Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CSS, is it possible to target class property identified by index number?

I'm trying to target a class element (appearing more than once in the DOM) by its index or iteration, strictly using CSS.

I know of several different ways of achieving this: I could toss the element(s) in an array and retrieve a specific index of said element (Javascript). I could label the element I'm trying to target with an #ID. I could refine the targeted element by specifying an attribute (.element[href="link"]). The pseudo-class :first-child and :last-child only target the children of that (parent) element (Duh!).

Example: I have a .class appearing 5 times within my DOM and I want to affect the CSS properties of the 3rd iteration of that .class element.

I wish there was a pseudo-class of .element:index-3. There's probably something out there that let's you do just that.

like image 391
Justin Ward Avatar asked Oct 27 '12 23:10

Justin Ward


People also ask

How do you target a class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

Can we use index in CSS selector?

A CSS selectors provides more ways for matching elements by examining where they are situated in the document metatree. They are considered to be child-indexed pseudo-classes since the position or order of the element determines the type, attributes, or IDs attached to it.

How do I identify a class in CSS?

In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).


1 Answers

If I understand you correctly, you want to style the element with the content "Me!" in this example:

<body>
  <p>Not me.</p>
  <p class="me">Not me.</p>
  <div><p class="me">Not me.</p></div>
  <p class="me">Me!</p>
  <div><div><p class="me">Not me.</p></div></div>
  <p class="me">Not me.</p>
</body>

This should be possible In some cases (see below) it is possible with the pseudo-class :nth-of-type:

.me:nth-of-type(3) {color:red;}

As ScottS noted in the comments, this is only possible if all classes are on the same element type (e.g. p).

like image 193
unor Avatar answered Oct 22 '22 03:10

unor