Dabbas
Dabbas

Reputation: 3228

How to use rule inside another rule in css?

What I'm asking for is a bit strange I think, but I have no other way.
Is there a way to do this pseudo css rule in real life:
let's say I have rule:

.myCssRule1{ color:red; }

And I can't (don't want) to change it but I need to use it in another rule I will made like this:

.myCssRule2{  
   .myCssRule1
}

Just like calling method from inside another one.
Any native way or JS library to do it ?

Upvotes: 2

Views: 5134

Answers (4)

voidstate
voidstate

Reputation: 7990

This is now part of the CSS standards: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_nesting/Using_CSS_nesting

No need for SASS or LESS to do this any more.

You may want to also explore CSS combinators which are very useful when nesting rules: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators

Upvotes: 1

cowls
cowls

Reputation: 24354

You can use a CSS Framework like LESS to do this.

Code you write using LESS is then compiled into "native" css files.

An example here: check out Mixins: http://lesscss.org/

Below code taken straight from that LESS link

// LESS

.rounded-corners (@radius: 5px) {
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
  -ms-border-radius: @radius;
  -o-border-radius: @radius;
  border-radius: @radius;
}

#header {
  .rounded-corners;
}
#footer {
  .rounded-corners(10px);
}

Using less this is compiled to:

/* Compiled CSS */

#header {
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  border-radius: 5px;
}
#footer {
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  -ms-border-radius: 10px;
  -o-border-radius: 10px;
  border-radius: 10px;
}

Upvotes: 2

Hubro
Hubro

Reputation: 59378

You can't mix styles into selectors in that way using pure CSS. The way I would recommend achieving your result is to create a class with the properties you want shared, for example:

.red {
    color: red;
}

And apply that class to all the elements you want to be red. Any HTML element can have any amount of classes:

<div class="myCssRule1 myCssRule2"></div>

A better way (in my opinion) is to make use of a CSS preprocessor, which is a language often similar to CSS that gives you extra features, but compiles down to a normal CSS style sheet. My favourite one is Stylus, but you should also check out LESS, Sass and Compass.

Upvotes: 1

cimmanon
cimmanon

Reputation: 68339

You would need a CSS preprocessor to do that. The most popular are Sass and LESS.

Upvotes: -1

Related Questions