Go back

CSS Selectors

CSS Selectors

There are many ways we can select/address an element in CSS.

  1. Using the tag name. For example, if we want to style all <h1></h1> tags on a page we can use the tag name to target the element.

    h1{
         color: #fcfcfc; /* makes the text gray */
     }
  2. Using class name If we want to target all the elements with the class “red” (for example: <h3 class="red"></h3>) we can use a . with the class name to target the group of elements with that class.

    .red{
         color: #fc2492; /* a magenta text */
    }
  3. Using ID If we want to target an element with the ID “xyz” (for example: <h3 id="xyz"></h3>) we can use a # with the ID to target the element with that ID.

    #xyz{
         color: #fc2492ff; /* a magenta text */
    }
  4. Universial Selector We can use the * as the universial selector.

  5. CSS Combinators There are different combinations we can use to target different elements -

    a. Immidiate child: div > p gets all the p tags which are immidiate child of div tag b. All descendents: div p gets all the p tags inside div tag c. Selector list: button, input gets all the button and input tag. d. Next sibling: #box+button gets the button tag right after the element with the id #box

  6. Psudo Classes In CSS we have some psudo classes denoting states of elements, different states of form elements, or element position.

    Example:

    a:hover{
        /* style the hover state of all anchor (a) tag */
    }
    div:nth-child(odd){
        /* styles all the odd position div tags */
    }
    input:disabled{
        /* styles the input element when it is disabled */
    }
  7. Psudo elements In CSS psudo elements target selective parts of an element. Example - ::before, ::after, ::first-letter, ::first-line

    Example:

    div::first-letter{
        /* styles the first letter */
    }

Fun note: In VSCode if you hover over a css selector it shows the definition provided by MDN for that selector