L
L
lexstile2021-08-16 23:56:28
css
lexstile, 2021-08-16 23:56:28

How to apply styles to all descendants with a given class except the last one?

You need to apply styles through the class to all elements with the .block class except the last one.
Elements .test1 , .test2 must have styles, test3 must ignore styles.
That is, you need something like this - :last-of-type , but for a class (as I understand it, this pseudo-class is for a tag).

<div class="wrap">
  <div class="test1 block">Тест 1</div>
  <div class="test2 block">Тест 2</div>
  <div class="test3 block">Тест 3</div>
  <div class="test4">Тест 4</div>
  <div class="test5">Тест 5</div>
</div>

You need to do this (this does not work):
.block {
    margin-top: 0;

    &:not(:last-of-type) {
      margin-bottom: 40px;
    }
  }

Or like this:
.block {
    margin-top: 0;
    margin-bottom: 40px;

    &:last-of-type {
      margin-bottom: 0;
    }
  }


UPD: It should also work , but you need not be tied to a number, since the number of blocks is unknown.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Edward Treit, 2021-08-17
@EdMSL

Yes, it's not that easy to do. But if you only need to remove the indent, then you can cheat like this:

.block {
  margin-bottom: 40px;
}

div[class~="block"] + div:not([class~="block"])  {
  margin-top: -40px;
}

https://codepen.io/EdMSL/pen/LYyoepW

A
Artem Zolin, 2021-08-17
@artzolin

.block {
  margin-top: 0;
  &:not(:last-child) {
    margin-bottom: 40px;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question