Scott Clark Scott Clark - 2 months ago 6
CSS Question

CSS How To: Easily make all rules check for 1 ancestor

For example:

.main .box{
//rules
}


These rules will affect all
box
so long as they are inside of a tag of class
main


Lets say I have about 100 rules on this page and all of them are only to be enforced if inside a tag of class
main
. Is there an easier way to enforce this or do I have to place
.main
in front of every rule in the .css? If there a way to declare this simply at the top of the .css?

Answer

The short answer is "no". In plain CSS, you will have to put .main in front of every rule in the file. The longer answer is "sort of". If you are using a pre-processor like LESS or SASS, you can do something like the following:

.main {
    .box {
        //rules
    }
    // rinse and repeat
}

That said, if this is the only thing you need a pre-processor for, it's likely to be overkill. In many cases, pre-processors can help make your code easier to maintain and write (such as with situations like your example). However, you should evaluate your own needs against the pros and cons to decide whether it makes sense in your case.

Comments