CMTV
CMTV

Reputation: 2851

CSS selector scoping

Let's assume we have this code:

<section id="block">
  <p>Some Text</p>
  <p class="test">Some Text With Class 'test'</p>
  <p>Some More Text</p>
</section>

<p>Some Text</p>
<p class="test">Some Text With Class 'test'</p>
<p>Some More Text</p>

So I want to style <p> and <p class="test"> inside <section id="block"> only.


This CSS can be used to do so:

#id p {
  ...
}

#id .test {
  ...
}

However I think it is a bit distracting in case of long ids such as #my-very-long-id for example.


Another way to achieve this is to use <style scoped></style> tags.

But it is not really convenient to have CSS code in HTML and furthermore it is mostly not supported by most browsers (as caniuse.com says).


My question: is there a way to declare some kind of selector scoping inside CSS?

It would be cool to have something like this:

@scope(#id) {
  p {
    /* ... */
  }

  .test {
    /* ... */
  }
}

Upvotes: 2

Views: 192

Answers (2)

Radu Onisor
Radu Onisor

Reputation: 23

You can do this:

#id {
  p {
    /* ... */
  }

  .test {
    /* ... */
  }
}

only with LESS or SASS, not with css.

Why don't you do

#id > p{ your style }

so every p inside that id will take that style. And for more aditional style for class .test , you can declare it separated.

Upvotes: 0

Resheil Agarwal
Resheil Agarwal

Reputation: 155

You can go for http://sass-lang.com/guide This might help you !

Upvotes: 2

Related Questions