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

Categories

0 votes
950 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 Reply

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...