CSS Selectors

CSS Selectors

Table of contents

No heading

No headings in the article.

What are CSS selectors?

CSS selectors define the pattern to select elements to which a set of CSS rules are then applied.

Types of CSS selector

  1. Universal Selectors

    A universal selector is used where we need to target the whole webpage. Optionally, it may be restricted to a specific namespace or all namespaces.

    Example:

     * {
       color: blue;
     }
    
  2. Type Selector

    Selects all elements that have the given element name.

    example:

     p{
     background-color: #BF3325;
     }
    
  3. Class Selectors

    Selects all elements that have the given class attribute.

    Example:

     .call{ 
     background-color:#BF3312
     }
    

    It will select the element with the calling class and will change its background color to the given color.

  4. ID Selector

    Selects an element based on the value of its id attribute. There should be only one element with a given ID in a document.

    Example:

     #name{
     color:#383CC1
     }
    
  5. Chained Selector

    When we want to go for certain conditions where we need two or more cases we use chained selectors, like if we need a and b conditions to be true.

     li.bg-one.text-white
    

    The above example is selecting two classes bg-one and text-white in the list.

  6. Combined Selector

    It is denoted by,(comma) which selects the specified tags. It can be two or more elements at once.

    Example:

     element1,element2{style properties}
     div,span,p,li{ color:red }
    

    will target the div, span, li and p tags from the documents and make the color red.

  7. Descendants(Inside an element) Selector

    when we need to select anything inside the element where there are different options to choose we use

    Example:

     div ul li
     {
     background-color:red;
     }
    

    above will select the list when the list is under the unordered list and is inside the div.

  8. Direct Child Selector

    It selects the direct child inside the element. It is denoted by >

    Example:

     div>p
     {
     background-color:cyan
     }
    
  9. Sibling Selector

    This selector can be used by the "~" or "+" sign. It is used to select the elemt next to the sibling class

    Example:

     .sibling+p
     {
     color:green;
     }
    

    The above code will select the paragraph next to the sibling class.

  10. Attribute Selector

    Selects the attribute from the element that needs to be target.

    Example:

    a[href="google"]{
    color:rgb(222,0,0)
    }
    

The above anchor tag will get selected wherever the value of the href is google.