Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you scope CSS files so that they only apply to the descendants of a given element?

Tags:

css

Given a css file, is there a way to scope the entire file so that it only applies to elements within a given element:

e.g. given:

<div id="container">
   <span class="some_element"/>
   <!-- etc -->
</div>

Is there a way to scope an entire css file to apply to all elements within "container" without prepending #container to every single css clause?

like image 384
oym Avatar asked Oct 20 '11 19:10

oym


1 Answers

I’m afraid not. Some CSS pre-processors allow you to write code that achieves the same thing though.

E.g. LESS implements nested rules:

/* This LESS code... */

#header {
  h1 {
    font-size: 26px;
    font-weight: bold;
  }
  p { font-size: 12px;
    a { text-decoration: none;
      &:hover { border-width: 1px }
    }
  }
}

/* ...produces this CSS */

#header h1 {
  font-size: 26px;
  font-weight: bold;
}
#header p {
  font-size: 12px;
}
#header p a {
  text-decoration: none;
}
#header p a:hover {
  border-width: 1px;
}

And Andy mentioned SASS, which does the same thing.

like image 82
Paul D. Waite Avatar answered Nov 06 '22 07:11

Paul D. Waite