Why no nesting in CSS? [closed]
Seems like it would be a nice way to have css structured. Are there cases that would make this impossible?
I am thinking of something like the following:
table#myTable{
thead{
color:red;
}
tbody{
color:blue;
td.title{
background-color: green;
}
}
}
I can't answer why CSS doesn't have this feature. There are a few systems such as LESS (http://lesscss.org/) that allows you to write structures like this, and then 'compile' them down to regular CSS.
Nested example in LESS: (from that link)
Nested Rules Rather than constructing long selector names to specify inheritance, in Less you can simply nest selectors inside other selectors. This makes inheritance clear and style sheets shorter.
#header {
color: red;
a {
font-weight: bold;
text-decoration: none;
}
}
Because at the time of the spec writing no one probably thought of the idea, or not enough people thought it would be useful.
You can use SASS, though: http://sass-lang.com/
Example syntax:
table.hl
margin: 2em 0
td.ln
text-align: right
li
font:
family: serif
weight: bold
size: 1.2em
It would be nice, but that's the way CSS is designed and organized doesn't support that.
However, there are CSS preprocessors which allow you to code this way, and then process it into real, valid CSS - such as LessCSS.
You may still indent your selectors according to your document structure:
body {
font-size: 1.4em;
color: #666;
}
#Header {
/* stuff */
}
#Header ul {
/* stuff */
}
#Header il {
/* stuff */
}
#Content {
/* stuff */
}
Other than the sporadic background-image: url(''); properties generally don't run very long, and during development this might help you keep organized. I personally prefer unindented CSS because I often let Textmate reformat my stylesheets.
精彩评论