15

I have 2 classes with different styles. Can I apply the styles from one class to another when within a media query with LESS?

So with the following CSS an element with a class of .one is blue but not bold. With a set media query I also want it to be bold and 2ems.

.one {
 color: blue;
}

.two {
 font-weight: bold;
 font-size: 2em;
}
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • 1
    Not sure of the exact requirement but if you just want some extra properties, it can be done with pure CSS itself. If you want to define a class (or mixin) and re-use it then you could use Peter's answer. – Harry Jan 13 '15 at 14:08

3 Answers3

16

Try

.one {
 color: blue;
}

.two {
 font-weight: bold;
 font-size: 2em;
}
@media screen {
   .one{
       .one;
       .two;
   }
}

will create this css:

.one {
  color: blue;
}
.two {
  font-weight: bold;
  font-size: 2em;
}
@media screen {
  .one {
    color: blue;
    font-weight: bold;
    font-size: 2em;
  }
}
Grim
  • 1,938
  • 10
  • 56
  • 123
  • I need to apply the rule within a media query – Evanss Jan 13 '15 at 12:28
  • @jdln ok, check it now. – Grim Jan 13 '15 at 12:34
  • I need to do this without adding a class to the HTML. Reason being I want to sometimes add the class in different media queries, and sometimes with JS. It will keep my LESS much cleaner if I can simply extend the styles from the class in a media query. – Evanss Jan 13 '15 at 13:59
  • You dont have to add a class to the HTML. – Grim Jan 13 '15 at 14:02
14

:extend can do this. In the code below if .class2 is in a media query then for that width the styles from .class will be applied.

.class {
  some rules here 
}

.class2 {
    &:extend(.class);
    ...
}

Does LESS have an "extend" feature?

Community
  • 1
  • 1
Evanss
  • 23,390
  • 94
  • 282
  • 505
1

You can use a mixin and a variable for the color

@default_color : "#000";
@color : blue;

.font-style(@c: @default_color) {
  color: @c;
  font-weight: bold;
  font-size: 2em;
}

.one {
 color: @color;
}

.two {
  .font-style()
}

@media (max-width:420px) { 
  .one {
    .font-style(@color)
  }
}

Codepen demo

In the demo above, resize the window to lesser width and you will find the text changing it's style.

anpsmn
  • 7,217
  • 2
  • 28
  • 44