📜 ⬆️ ⬇️

Style descriptions for multiple selectors listed simultaneously

Good day.

I want to share with the habrasoobshchestvu one useful property that is not so often used, although with proper use can reduce the size of css and html code. It is about the possibility of registering css-properties for elements with several selectors specified simultaneously.


This is done quite simply - you need to list the selectors in a row, without spaces (with a space, as you know, you will get a descendant selector).
')
 <style>
 .red_bg {background: # f00;  }
 .red_text {color: # f00;  }
 .red_bg.red_text {color: #fff;  } / * this rule will apply when
                                      both previous classes are indicated simultaneously * /
 </ style>

 <div class = "red_bg">
 this is text on red background
 </ div>

 <div class = "red_text">
 this is red text
 </ div>

 <div class = "red_bg red_text">
 on a red background, the text became white
 </ div>


Similarly, you can set style descriptions for any number of class selectors simultaneously. For example, the entry

 <style type = "text / css">
 .red_bg.red_text.bordered {...}
 </ style>

will be applied only to those elements that have three classes specified at the same time.

In addition, class selectors can be combined with identifiers selectors #id:

 <style type = "text / css">
 # menu.red_text {...} / * usually class = "red_text" does one thing,
                           and for #menu the same class can add another description * /
 </ style>

and with attribute selectors:

 <style type = "text / css">
 h1 {background: # 000;  color: #fff;  }
 .notice {color: # 00f;  }

 h1.notice {color: # ee8;  }
 </ style>

 <p class = "notice"> The text in the block with class = "notice" is blue. </ p>

 <h1> The first level heading is white on a black background. </ h1>

 <h1 class = "notice"> The first level heading with the class = "notice" becomes light,
  because  blue on black cannot be read </ h1>


Sometimes it was necessary to see how extra structural blocks were added to implement this functionality, and separate css rules were written for them as descendants. As you can see, this can be easily avoided by keeping the markup clean and the hair soft and silky :)

That's all, I hope someone will find this useful.

Source: https://habr.com/ru/post/40560/


All Articles