A brief introduction to CSS selectors

What is CSS selector?

It is first part of Css Rule. It is used to select the content you want to style. The element or elements which are selected by the selector are referred to as the subject of the selector.

Types of CSS selectors :-

  • Universal selector (*).
  • Class and Id selector (. , #).
  • Element Selector .
  • Attribute Selector (input[type="text"]).

Types of combination selector :-

  • Child selector (>).
  • Descendant selector (space).
  • Adjacent sibling selector (+).
  • General sibling selector (~).


Universal selector:

It selects any type of elements in an html page. As asterisk (*) is used to denote Universal selector. It is used when you to style for all the elements within an element of an html page.

Example

*{
    padding:0;
    margin:0;
    font-family:sans-serif;
  }

Class and Id selector:

Class selector:

  • The Class selector selects html elements with a specific class attribute.
  • Full stop (.) is used to denote class selector.

    Example

    .home{
             display:flex;
             align-items:center;
    }
    

    Id selector:

    • The Id selector selects the id attribute of an html element to specific element.
    • Hash (#) is used to denote Id selector.

      Example

#home{
              display:flex;
              align-items:center;
 }

Element Selector:

  • The element selector selects the html element by name.

    Example

    h1{
       color:orange;
       font-size:26px;
    }
    p{
     font-weight:500;
     font-size:16px;
    }
    

Attribute Selector

  • Attribute selector describes those are applicable to matching attributes or attribute values of elements of html page.
  • Types of attribute selectors:
    • [attribute]:Select element with matching attribute name.
    • [attribute="value"]:Select element with matching attribute name.
    • [attribute~="value"]:Select element whose attribute name & one of white space- separated list of words matching.
    • [attribute|=val]:Select element whose attribute name is matching & attribute value is either same as "val" or started with "val" & followed by(-).

Example

input[type="text"]{
           color:red;
}

Child selector:

  • It is used to select all child elements with a particular parent element.

Example

ul > li {
  background-color: brown;
}

Descendant selector:

  • We can use this selector to select elements that are inside of other elements (child elements).

    Example

  .lists ul .list-item {
    background-color: black;
    color: white;
   }

Adjacent sibling selector:

  • It is used to select the adjacent sibling of element but it will only select first one.

    Example

p + li {
    background-color: green;
}

General sibling selector:

  • It used to select all elements that follow the first element such that both children of same parent.

    Example

p ~ li {
    background-color: pink;
}