Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting CSS classes

Can I do something like the following?

.class1{some stuff}  .class2{class1;some more stuff} 
like image 646
kralco626 Avatar asked Dec 30 '10 17:12

kralco626


People also ask

Can I nest CSS classes?

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.

How do nested CSS classes work?

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.

What does nesting mean in CSS?

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.

How do you nest things in CSS?

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.


2 Answers

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.

like image 71
etoxin Avatar answered Sep 20 '22 06:09

etoxin


Not possible with vanilla CSS. However you can use something like:

  • Sass

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

  • Less

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;   } } 
like image 41
Sarfraz Avatar answered Sep 19 '22 06:09

Sarfraz