The idea of precedence with HTML tags is very simple. What would happen if the tag tells the browser to display the font in blue while the tag in the body tells the browser to display the text in green? The rule of precedence in HTML is that the inner-most nested tag takes priority over all other tags. So if you had something like:
This demonstrates the precedence of nested HTML tags. First there is A, which is in red, then we have B which is in green, and finally we have C which is in blue. This is easy to see because each letter comes directly after the tag which defines the color attribute to the red, green, and blue. Next, after the letter C (which is in blue since it comes right after the tag that defines the color attribute as “blue”), we have . The question is, which opening tag does this close? Is it in order that it was defined? Will it close the tag that defines the color to be red, or the one that defines it to be green, or is it the one that defines it to be blue?
The first thing to notice is that the three tags that have defined the red, green, and blue tags have not yet been closed. The next thing to note is that HTML tags are always nested. This means that the inner-most tag between the red, green, and blue is the one that is defined last, which is blue. Blue is inside of green, and green is inside of red, which makes red the outer-most tag.
The inner-most tag will get closed first, which is blue. The that is directly after C will close the blue tag. The next which is after the letter D will close the next inner-most tag, which is green. Finally, the that is after the E will close the outer-most tag, which is red.
So looking at the events as they occur, we see something like this:
1. Set font color to Red
2. Write the letter A (written in Red)
3. Set font color to Green
4. Write the letter B (written in Green)
5. Set the color to Blue
6. Write the letter C (written in Blue)
7. Close the Blue tag (color now set to Green)
8. Write the letter D (written in Green)
9. Close the Green tag (color now set to Red)
10. write the letter E (written in Red)
11. Close the Red tag (color now set to default, or back to what it was before the color was set to red at the very start, for example, what it was in the tag)
From this, you can see how the precedence of nesting is done. The inner-most nested tag has the highest priority and the priority decreases as you go toward the most outer-nested tag.
In the next tutorial, we will talk about a related topic, HTML tag scope.