简体   繁体   中英

Is there a nicer way to use nested SASS & selectors in this scenario?

I need to select a child of an element but it's based on :last-of-type on the parent.

I've tried:

&:last-of-type {
  &__content {
    border-bottom: 0;
  }
}

Which doesn't work because of the way SASS constructs.

I've ended up with:

.assignment-selection {
  &__list-item {
    &__content {
      border-bottom: 1px solid;
    }
    &:last-of-type {
      .assignment-selection {
        &__list-item {
          &__content {
            border-bottom: 0;
          }
        }
      }
    }
  }
}

Is there a nicer/more efficient way of writing this?

This should do it

&:last-of-type > &__content {
  border-bottom: 0;
}

You can solve this with regular CSS like this (if this is an option)

css:

.parent>li {
  border: 1px solid red;
}

.parent:last-of-type>li {
  border: 1px solid green;
}

html:

<div class="parent">
  <li class="child">text</li>
</div>
<div class="parent">
  <li class="child">text</li>
</div>
<div class="parent">
  <li class="child">text</li>
</div>

this is the related fiddle: http://jsfiddle.net/ugskwa7t/

Just because SASS allows nesting doesn't mean we should always nest since it makes CSS a bit unreadable, even more so in the Browser's dev tools which makes code harder to debug.

.assignment-selection {
  &__list-item {
    &__content {
      border-bottom: 1px solid;
    }
  }
}

.assignment-selection:last-of-type {
  &__list-item {
    &__content {
      border-bottom: 0;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM