ID vs Class


What would happen if an HTML element has an ID and a Class selectors assigned to it, and we add the same CSS attribute to both, but with different values? Which one takes priority?

What is the difference?

An id value may only appear once in a single document. A class value can be applied to any number and type of elements.

id has higher specificity than class.

     style   id   class  type     <-- attribute over element type
       1      0     0      0
       0      1     0      0
       0      0     1      0
       0      0     0      1
<--- higher specificity
            lower specificity --->


Where we see this play out is in the style sheet, and how the browser distributes selector rules. The cascade is figuratively like a running brook. It has a before and after (higher and lower).

When we read lower in the cascade it means the rule is parsed later than. Since rules are declarations (imperative) they get punched in to whichever element nodes they apply. This may overwrite rules that were parsed earlier and distributed to the DOM.

Create a blank template and copy it everytime you want a fresh page.

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">



Put these lines into the head, after the title

    #unit {
        color: purple;
    .view {
        color: maroon;
    p {
        color: black;

Now insert these lines to the body…

<p style="color: blue" id="unit" class="view">style</p>
<p id="unit" class="view">id</p>
<p class="view">class</p>


The id attribute has been duplicated above for demonstration only. It is ignored in the first example and only applies in the second example.