Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Syntax to select multiple elements under a class

Tags:

css

HTML:

<div class="home">
 <div class="a">
   A content
 </div>
 <div class="b">
   B content
 </div>
 <div class="c">
   C content
 </div>
 <div class="d">
   D content
 </div>
 <div class="e">
   E content
 </div>
</div>

To apply common styles for a,c and e children under home class we can use multiple css selectors as written below.

CSS:

.home .a,.home .c,.home .e{
 background-color:#ccc;
}

Question: What is the shorter version of the above css?

Now as a c and e are common children of home. Instead of repeating .home again and again how can I write a shorter syntax to select class a, b and c that are under home class.

Maybe something like:

.home(.a,.c,.e){
 color:#ccc;
}

I know it is wrong but just gives a clear idea about my question here, what I am looking for.

like image 253
Kiran Dash Avatar asked Jul 24 '26 04:07

Kiran Dash


2 Answers

The code .home(.a,.c,.e) won't work, and there is no OR operator for CSS selectors. home .a,.home .c,.home .e is the shortest way.

But here a few selectors that might help you:

.home div { } /* all divs in home */
.home > div { } /* all divs that are a direct child of .home */
.home * { } /* all elements in .home */
.home > * { } /* all direct children of .home */

There also exist CSS preprocessors, like SASS and LESS that give you more possibilities.

like image 100
LinkinTED Avatar answered Jul 26 '26 06:07

LinkinTED


Use the child selector '>'.

CSS:

.home > div {
  color: #ccc;
}
like image 40
Asaf David Avatar answered Jul 26 '26 05:07

Asaf David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!