Can I do something like the following?
.class1{some stuff} .class2{class1;some more stuff}
When we use a CSS preprocessor like Sass or Less, we can nest a CSS style rule within another rule to write clean and understandable code. This nesting rule is not supported yet in native CSS. At the moment, it is a working draft and only available for discussion.
Nested rules are defined as a set of CSS properties that allow the properties of one class to be used for another class and contain the class name as its property. In LESS, you can use class or ID selectors to declare mixin in the same way as CSS styles.
Nesting is a shortcut to create CSS rules for multiple selectors for a specific property. So, instead of rewriting the same set of properties for the different selectors, we can simply nest selectors inside other selectors.
To nest a selector, you simply separate them with a space. This will make paragraph tags inside main have one font size, and paragraph tags inside either header or footer have another font size. Descendant selectors target all elements inside the other, no matter how deeply nested it is.
Update 1: There is a CSS3 spec for CSS level 3 nesting. It's currently a draft. https://tabatkins.github.io/specs/css-nesting/
Update 2 (2019): We now have a CSSWG draft https://drafts.csswg.org/css-nesting-1/
If approved, the syntax would look like this:
table.colortable { & td { text-align:center; &.c { text-transform:uppercase } &:first-child, &:first-child + td { border:1px solid black } } & th { text-align:center; background:black; color:white; } } .foo { color: red; @nest & > .bar { color: blue; } } .foo { color: red; @nest .parent & { color: blue; } }
Status: The original 2015 spec proposal was not approved by the Working Group.
Not possible with vanilla CSS. However you can use something like:
Sass makes CSS fun again. Sass is an extension of CSS3, adding nested rules, variables, mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.
Or
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.
Example:
#header { color: red; a { font-weight: bold; text-decoration: none; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With