Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS-Less class extend class with pseudo class

I was wondering how I could do something like the following with less css:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.btn-foo {
  .btn;
  &:hover {
    .btn:hover;
  }
}

Of-course this is just an example, what need to point is if there is any way to extend the pseudo-class in order to avoid re-type the properties of :hover pseudo class everywhere I need them. I know I could create a mixin for that but I'm wondering if I could avoid it.

Thanks

like image 948
panosru Avatar asked Feb 05 '12 21:02

panosru


People also ask

Can CSS classes combine with pseudo classes?

If you're talking about pseudo-classes, then yes, you can combine them in any order.

Can you use multiple pseudo class selectors with an element?

Pseudo-classes are allowed anywhere in selectors while pseudo-elements may only be appended after the last simple selector of the selector. This means your syntax is correct according to CSS2.

Can pseudo-elements and pseudo classes Cannot be combined?

There are no special rules around combining pseudo-classes and pseudo-elements, besides the one rule that says there can only be one pseudo-element per complex selector and it must appear at the very end.


2 Answers

UPDATE: If you can't modify external files just redefine the selectors, and add missing states:

.btn {
  // not adding anything here, won't affect existing style
  &:hover {
    // adding my own hover state for .btn
    background: yellow;
    ...
  }
}

// this will make your foo button appear as in external style
// and have the :hover state just as you defined it above
.btn-foo {
  .btn;
}

Better now? :)


You don't need pseudo class. It will just work :)

Try this:

.btn {
  background: yellow;

  &:hover { // define hover state here
    background: green;
  }
}

button {
  .btn;
}

Each <button class='btn'> element you create will inherit whatever was defined, including hover state. I think it's one of the main amazing features of LESS.

Hope this helps.

like image 100
bzx Avatar answered Sep 19 '22 05:09

bzx


In Less 1.4.0(1.4.1?)

This:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.btn-foo:extend(.btn all) { 
}

Expands to this:

.btn,
.btn-foo {
  color: black;
}
.btn:hover,
.btn-foo:hover {
  color: white;
}

Be cautious though, this:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.abc .btn {
  margin: 2px;
}

.btn-foo:extend(.btn all) {

}

Will output this:

.btn {
  color : black;
}

.btn:hover {
  color : white;
}

.abc .btn {
  margin: 2px;
}

.btn-foo:extend(.btn all) {

}

I have not looked into SASS more than half an hour, but I believe the later case is its default (or only) @extend behavior.

like image 35
John Avatar answered Sep 20 '22 05:09

John