0

I have a list of items related to each other

<dl>
    <dd data-grupo="1">1. Tomatoes</dd>
    <dd data-grupo="1">2. Cucumbers</dd>
    <dd data-grupo="1">3. Mushrooms</dd>
    <dd data-grupo="2">4. Apples</dd>
    <dd data-grupo="2">5. Mangos</dd>
    <dd data-grupo="2">6. Pears</dd>
    <dd data-grupo="2">7. Oranges</dd>
</dl>

How can I select the first and last sibling in the group data-grupo="1" and data-grupo="2" to make them red and blue? Using only css

I've tried

dl dd[data-grupo="1"]:first-child,
dl dd[data-grupo="1"]:last-child{

  background: red;

}


dl dd[data-grupo="2"]:nth-child(1),
dl dd[data-grupo="2"]:nth-child(-1){
  background: blue;

}
chepe263
  • 2,774
  • 22
  • 38
  • 1
    Does this answer your question? [How can I select the last element with a specific class, not last child inside of parent?](https://stackoverflow.com/questions/7298057/how-can-i-select-the-last-element-with-a-specific-class-not-last-child-inside-o) – Erik Philips Jul 29 '22 at 02:04

1 Answers1

0

ou'll notice that one of what you want actually seems to work:

dl dd[data-grupo="1"]:first-child,
dl dd[data-grupo="1"]:last-child{

  background: red;

}
dl dd[data-grupo="2"]:nth-child(1),
dl dd[data-grupo="2"]:nth-child(-1){
  background: blue;

}
    <dl>
        <dd data-grupo="1">1. Tomatoes</dd>
        <dd data-grupo="1">2. Cucumbers</dd>
        <dd data-grupo="1">3. Mushrooms</dd>
        <dd data-grupo="2">4. Apples</dd>
        <dd data-grupo="2">5. Mangos</dd>
        <dd data-grupo="2">6. Pears</dd>
        <dd data-grupo="2">7. Oranges</dd>
    </dl>

The problem is your understand of how selectors work. Selectors are an all or nothing.

dl dd[data-grupo="1"]:first-child

This doesn't mean give me the first child of elements in the selector dd[data-grupo="1"].

It means, turn red only the target element is in a dl is a dd[data-grupo="1"] AND is :first-child (is the first child).

That's why the it works for the :first-child and not the :last-child because the last child of dl is a <dd data-grupo="2"> not dd[data-grupo="1"].

Erik Philips
  • 53,428
  • 11
  • 128
  • 150