您可以将CSS文件作为范围,以便它们仅适用于给定元素的后代吗?

oym*_*oym 10 css

给定一个css文件,是否有办法对整个文件进行范围调整,使其仅适用于给定元素中的元素:

例如:

<div id="container">
   <span class="some_element"/>
   <!-- etc -->
</div>
Run Code Online (Sandbox Code Playgroud)

有没有办法将整个css文件的范围应用于"容器"中的所有元素,而不必预先#container设置每个css子句?

Pau*_*ite 7

恐怕不是.一些CSS预处理器允许您编写实现相同功能的代码.

例如,LESS实现嵌套规则:

/* 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;
}
Run Code Online (Sandbox Code Playgroud)

而安迪提到SASS,它做同样的事情.


alb*_*ert 6

您可以scoped在<style>元素上使用该属性,尽管几乎没有浏览器支持它.在你的例子中:

<div id="container">
    <style scoped>.some_element{}</style>
    <span class="some_element"></span>
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个jQuery Polyfill:http://thingsinjars.com/post/360/scoped-style/