Paul Dessert
Paul Dessert

Reputation: 6389

Is there a way to shorten css selectors?

I have:

#signUpForm h1, #signUpForm p{
    color: #fff;
}

Is there a way to shorten this such as:

#signUpForm h1, p{
    color: #fff;
}

Or do I need to create a new comma separated selector each time, as in my first example?

Upvotes: 1

Views: 406

Answers (3)

user663031
user663031

Reputation:

Use :any.

#signUpForm :any(h1,p) { }

Browser support varies. You may need to do -webkit-any etc.

See https://developer.mozilla.org/en-US/docs/Web/CSS/:any. See also the proposal for the similar :matches CSS4 pseudo-class at http://dev.w3.org/csswg/selectors4/#matches.

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157294

It depends on the properties you are specifying and the elements you want to target, if its jut about color then you can write

#signUpForm {
    color: #fff;
}

Because color property will be inherited by h1 as well as p but think of a scenario where you want to apply font-weight so here you cannot use the above selector as font-weight won't be inherited by h1 tag.

If you want, you can use CSS pre processors like LESS or SASS where you can write like

#signUpForm {
    h1, p {
       font-weight: 100;
    }
}

But again, as I said, it depends on the properties you are writing, because some are inherited by the child elements and some are not, so even if you use color like

#signUpForm {
    h1, p {
       color: #fff;
    }
}

Makes no sense because that is equivalent to #signUpForm { color: #fff; } unless you've specified a different color for h1 or p

Upvotes: 3

Bobadevv
Bobadevv

Reputation: 366

Have you thought of using Sass, you could do something like

#signUpForm{ 
    h1, p {
        color: #fff;
    } 
} 

Upvotes: 4

Related Questions