Goldentoa11
Goldentoa11

Reputation: 1760

CSS Selector Nesting

Is it possible to nest selectors within selectors? I have a lot of styles that are looking like this:

#header h1{
  ...
} 
#header img{
  ...
}
#header form{
  ...
}

and I want to condense them so that they would look something like this:

#header{
  h1{
    ...
  }
  img{
    ...
  }
  form{
    ...
  }
}

in order to improve readability. Is this possible in just plain old CSS?

Upvotes: 4

Views: 753

Answers (5)

SQRCAT
SQRCAT

Reputation: 5840

You might find things like

@-moz-document url-prefix() {
    .myDefinition {
    }
}

however. These are parsed by Firefox and can be used to provide Firefox-only CSS hacks, i am not sure though, how valid and standard-conform these are.

Upvotes: 0

Christoph
Christoph

Reputation: 51261

No it is not. However, if you use Preprocessors like SASS or LESS (to name only the most popular ones) it is.

Depending on what you need, you should look into one of those. They are definitely worth it, since they can ease your work significantly not only with nesting selectors but also introducing variables, mixins, loops and other handy stuff.

Introduction to and Comparison of CSS-Preprocessors

Upvotes: 2

tpower
tpower

Reputation: 56906

No it is not possible with plain old CSS.

But you can do with LESS or Sass. These two compile into CSS.

Sass produces CSS which can be indented like your required example.

#header{}
   #header h1{
     ...
   }
   #header img{
     ...
   }
   #header form{
     ...
   }

Upvotes: 0

Guffa
Guffa

Reputation: 700730

No, it's not possible in plain CSS. You need something like Sass or Less.

Upvotes: 0

user229044
user229044

Reputation: 239501

Not in vanilla CSS, but there are compile-to-CSS languages like LESS which allow you to use nested selectors.

My library of choice is Sass, which is now integrated into the Rails asset pipeline.

Upvotes: 2

Related Questions