开发者

Is there a way to use css pseudo classes as mixins with lesscss compilers?

开发者 https://www.devze.com 2023-03-06 13:58 出处:网络
I was trying to use a class with psuedo class in the less css mixin a:link{ color:#138CB4; text-decoration:none;

I was trying to use a class with psuedo class in the less css mixin

a:link{
    color:#138CB4;
    text-decoration:none;
}
开发者_StackOverflowa:visited{
    a:link;
    color:#84B6CD;
}

But out put I got is this, which an invalid css

a:link{
    color: #138CB4;
    text-decoration: none;
}
a:visited{
    a: link;
    color: #84B6CD;
}

Am I missing something here or mixins don't support pseudo classes yet.


I was a little confused by this at first, too, and found myself jumping through hoops to get it to work. Although your post is old enough that it might pre-date this functionality for all I know.

Anyway, if you're just trying to add additional styles to an existing style via pseudo-selectors, you can use the '&' operator. It works kind of like a 'this' keyword, and turns nesting into a simple combination. So you should be able to do:

a {
  color: #138CB4;
  text-decoration: none;

  &:visited {
    color: #84B6CD;
  }
}

This should compile out to something like:

a {
  color: #138CB4;
  text-decoration: none;
}

a:visited {
    color: #84B6CD;
}

Note that you can also use the & to combine 'sub-selectors':

.outer {
  color: blue;

  .error {
    //this will select elements that are .error inside-of/descending-from .outer
  }

  &.error {
    //This will select elements that are .outer AND .error
    color: red;
  }
}

The official definition is unfortunately hiding in plain sight in the Nesting Rules part of the documentation.


I don't believe that is how you use mixin's in Less.

You have defined the link pseudo class and then nested it under the visited pseudo class. This doesn't actually mean anything and is why your are getting that output.

If I think what you are aiming for is to re-use your link styles across :visited and :link, you actually will want this:

.link {
  color: #138CB4;
  text-decoration: none;
}

a:link {
  .link;
}

a:visited{
  .link;
  color: #84B6CD;
}


Not fully sure, what you want to achieve. But if you got tired of :link,:visted,:active (aka normal link) vs. :focus, :hover (hover styles), this works:

.anchor( @- ) {
    a, a:link, a:visited, a:active {
        @-();
    }
}
.anchorH( @- ) {
    a:focus, a:hover {
        @-();
    }
}

for example:

.anchor({
    background: #fff;
});

.anchorH({
    background: #ddd; /* darken on hover or focus */
});
0

精彩评论

暂无评论...
验证码 换一张
取 消