Home > Net >  how to seleect the last sibling in a group using only css?
how to seleect the last sibling in a group using only css?

Time:07-29

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;

}

CodePudding user response:

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"].

CodePudding user response:

Next sibling ( is Adjacent sibling):

.item   .item {
  /* the   operator selects adjacency */
  /* so this element is the next sibling */
}

First sibling:

.item { 
  /* this is effectively the first item */
  /* actually all items but the next rule overrides all but first */
}
.item   .item {
  /* is the rest of the items */
  /* the styles here must override the previous styles */
}

:first-of-type can work but requires the elements be the same (div, span, etc.)

Prev sibling:

.item:has(  .item) {
  /* check if this item has a next sibling */
  /* if it does then this is previous sibling */
}

Last sibling:

.item:not(:has(  .item)) {
  /* check if this item does not have a next sibling */
  /* if it doesn't, this must be the last one */
}

:last-of-type can work but requires the elements be the same (div, span, etc.):

  •  Tags:  
  • css
  • Related