1. Tag / Element selector Use the built-in html element name, e.g. div, body, span, p, ul etc. body { // style applies entire body(including child tags)... }
Enter fullscreen mode Exit fullscreen mode 2. Descendant selector <p> <a> direct descendant</a> <span><a> Indirect descendant</a></span> </p> <style> p a { // Apply styles to all 'a'(anchor) elements withing the paragraph p } </style>
Enter fullscreen mode Exit fullscreen mode 3. Child selector <p> <a> direct descendant</a> <span><a> Indirect descendant</a></span> </p> <style> p > a { // Apply styles to direct descendant only! } </style>
Enter fullscreen mode Exit fullscreen mode 4. Attribute selector Select an element with a specified attribute p [ id ] { // Apply styles to p element with id attribute set to anything } p [ id = 'fist' ] { // Apply styles to p element with id attribute set to 'first' }
Enter fullscreen mode Exit fullscreen mode 5. Select by Id Probably the most common selector ?? <body> <div id= "container" ></div> <div id= "not_a_container" ></div> </body> <style> #container { // style applies to div with id attribute set to 'container' } </style>
Enter fullscreen mode Exit fullscreen mode 6. Select by Class Second most common? No ? Ok. <body> <div class= "container" ></div> <div class= "not_a_container" ></div> </body> <style> .container { // style applies to div with class attribute set to 'container' } </style>
Enter fullscreen mode Exit fullscreen mode 7. Pseudo selectors Typically used to apply styles based on user events e.g. On mouse hover a :hover { font-weight : bold ; } // set the font weight of all links to bold on mouse hover
Enter fullscreen mode Exit fullscreen mode 8. Nth Child Selector This is best explained using an example <div> <p> Fist </p> <p> Second </p> <p> Third </p> <p> Fourth </p> </div> <style> p :nth-child ( 2 n ) { color : red ; } // This will affect each p element inside the parent div who ' s position is a // multiple of 2 </style>
Enter fullscreen mode Exit fullscreen mode
Top comments (0)