CSS Selectors

Before adding any css style we must select the items that are going to get affected, this article provides the information about how to select the elements we want.






Selectors



  • (space): descendant selector, not direct child but child of the previous element
  • (>): child selector, direct child of the previous element
  • (+): adjacent sibling selector, the next element that is at the same level that the previous element
  • (~): general sibling selector, an element which is at the same level than the previous element
  • (.): class selector, selects all HTML elements that share the same class
  • (#): id selector, selects the only element in the document with the id set to that value
  • (*): universal selector, selects every element in the document


Selector examples


Space Selector


CSS

element element { background: black; }

HTML

    <element>
        <notElement>
            <element>
        </notElement>
    </element>

Child Selector


CSS

element > element { background: black; }

HTML

    <element>
        <element>
    </element>

Adjacent Selector


CSS

element + element { background: black; }

HTML

    <element>
        <element>
        <element>
    </element>

General Sibling Selector


CSS

element ~ sibling { background: black; }

HTML

    <element>
        <sibling>
        <element>
        <sibling>
        <sibling>
    </element>

Class Selector


CSS

.element { background: black; }

HTML

    <element class="element"></element>
    <element></element>

ID Selector


CSS

#element { background: black; }

HTML

<element id="element"></element>
<element></element>


Universal Selector


CSS

* { background: black; }

HTML

<element id="element"></element>
<element class="element"></element>


Specificity

  • style attribute: HTML attribute to add on the HTML tag, 1000 points
  • id: HTML attribute to uniquely identify one element, 100 point per iteration
  • Class: HTML attribute to group one or more HTML elements, 10 point per iteration
  • pseudo-class: action/behaviour of an element such as :hover, 100100 point per iteration
  • attribute: an HTML attribute that adds some information like input[type="submit"], 10 point per iteration
  • elements: an HTML5 element, 1 point per iteration
  • pseudo-elements: a custom HTML element made by the user, 1 points