Search code examples
htmlcsssass

Is nesting possible with CSS (like it is with SASS)?


This might be a very stupid question, but I couldn't find anything and it seems so obvious: is nesting with CSS possible like with SASS?

For example, I want to define a h1 tag on a certain page, so I write:

body.certain_page h1 {
  font-size: 12px;
}

So far so good. If I want this style to apply to more than one page, I would write:

body.certain_page h1, body.other_page h1 {
  font-size: 12px;
}

Now when you define a lot of rules this way, it gets very tiring. It would be so much easier to write something like this:

body.certain_page, body.other_page {
  h1 {
    font-size: 12px;
  }
}

Like a media-query. Why is that not possible? Or am I missing something?


Solution

  • Well, as @destroy already answered, you cannot have nested selectors using CSS, that's why developers choose LESS and SASS preprocessors. The best thing you can do to minimize the CSS is my grouping common properties like

    div, p, i {
       color: #f00;
       /* All the three elements will have the same color */
    }
    

    You can also declare the base properties right in the parent selector so that they can be easily inherited and you don't have to call them again and again on each..

    body {
       font-size: 14px;
       font-family: Arial;
       color: #515151;
    }
    

    The above properties will be easily inherited by elements such as p, so you won't have to declare the font-family or font-size each time unless and until you want to have a different font-family for a particular element which can be over ridden by using a more specific selector like

    .class_name p {
       font-family: Open Sans, Arial;
    }
    

    You do have universal selectors which will also ease up over lengthy selectors, like say you want to color red all the elements nested inside a specific element having a class called .class_name so instead of doing

    .class_name p, .class_name div, .class_name fieldset {
       /* This is really bad */
    }
    

    Instead you can write the above as

    .class_name * {
       /* Much better */
    }
    

    Conclusion : Learn CSS Selectors, that's the only way you can figure out and you can optimize your CSS yourself, while selectors totally depend on the DOM, so there are no pre defined techniques but you should keep the selectors simple, not over complicated, else you will end up writing more and more specific rules which will lead to more 100 line of crappy CSS...


    Also, here's an handy tool by Google you can always use to optimize the performance.