4.3. More On Matching — Fundamentals Of Web Programming

4.3.2. Using an id attribute in a rule¶

Another common situation is that you have one particular paragraph that you want to have in a different color. You cannot just use a selector that matches the p tag as that will match all of the p tags. So in this case we need to somehow mark a particular paragraph so that we can have a selector that selects that paragraph and only that paragraph. This is where the id attribute is used. Any html tag can have an id attribute, which serves as a unique identifier for that tag. In fact, the value of the id attribute must be unique throughout the file.

In the example below we have two rules. One that changes the text to blue in all paragraphs. The second rule changes the font-size to 18pt for the paragraph that has the identifier of “abc456” The hashtag # is very important to this rule as it tells the css matcher that what comes after that hashtag must match the id attribute of some element. So, in fact the p is redundant in this example, and you could remove the p from the beginning of the selector and the rule would still work. In fact, you should try that now.

<html> <head> <style> p { color: blue; } p#abc456 { font-size: 18pt; } </style> </head> <body> <h1>Hello World!!</h1> <p id="xyz123">The paragraph text should be unchanged</p> <h2>I am not blue!</h2> <h1>Hello Again</h1> <p id="abc456">This is another paragraph with a different identifier.</p> </body> </html>

What do you think will happen if you change the second rule so that it sets the color to red? If you said that it will keep the first paragraph’s color blue but change the second to red, your are correct. Why does the second rule over-rule the first? Because the second rule is more specific. You might have thought it was because of the order of the rules, but in fact you can change the order of the two rules and try it and you will see that you still get the same result.

Từ khóa » H1 H2 H3 H4 H5 H6 Css