Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
879 views
in Technique[技术] by (71.8m points)

css - multiple nested selectors with variables in Less

I want to build some CSS along these lines:

h1,h2,h3,h4,h5,h6 {some rule}
h1 a,h2 a,h3 a,h4 a,h5 a,h6 a {color: inherit;}
h1 span,h2 span,h3 span,h4 span,h5 span,h6 span {another rule;}

It would be useful if I could create a variable like this:

@headings: h1,h2,h3,h4,h5,h6;

and then maybe do something like this:

@{headings} {
  & a {color: inherit;}
}

Unfortunately this gives me:

h1, h2, h3, h4, h5, h6 a {
  color: inherit;
}

Is what I want possible? This is a simple version of what I want to do but I would also find useful for working with HTML input types and other instances of multiple selectors that often appear together.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a Ruleset

If you define your heading group as a ruleset with a mixin call to set properties with, then you can do this:

@headings: {h1,h2,h3,h4,h5,h6 {.setProps()}};


& {
    .setProps() {
        & {
            some: rule;
        }
        a {
            color: inherit;
        }
        span {
            another: rule;
        }
    }
    @headings();
}

I've isolated the whole thing inside & just so the .setProps() can be localized (it would work without it, but it would be setting the .setProps() globally. Also, the nested & {} bracketing is not necessary, but I find that it helps show what the "default" for the @headings is going to be.

This can be used sequentially, if desired, like so:

& {
    .setProps() {  some: rule; }
    @headings();
}
& {
    .setProps() { a {color: inherit;}}
    @headings();
}
& {
    .setProps() { span {another: rule;}}
    @headings();
}

Both will output like so:

h1,
h2,
h3,
h4,
h5,
h6 {
  some: rule;
}
h1 a,
h2 a,
h3 a,
h4 a,
h5 a,
h6 a {
  color: inherit;
}
h1 span,
h2 span,
h3 span,
h4 span,
h5 span,
h6 span {
  another: rule;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...