Chuyển tới nội dung chính

id Selector

Earlier we show that element selectors can be used to define the element at which we want to apply our styles.
However, there are additional selectors. The id is one of them.
The id selector is created by a hashtag # followed by the selector’s name. The name can be anything but it cannot start with a digit or a dash.

The id selector selects elements with a specific id attribute (name).
Thus in our CSS the id will be:

#myname { border: 2px solid black; }

And in the HTML we will have:

<p id=”myname”>

This paragraph will have a black border 

When we use id selectors?

The basic rule is that id is unique. This means that one id will only exists once in the HTML page and that each element can contain only one id.
Since ids are unique, we only use them if we want to apply a specific style in an element to distinguish it from its surroundings elements.

For example we may have 100 paragraphs to which we have applied the following style:

p { text-align:center; font-size: 1em; }

Assume that we want one of these paragraphs to displayed in italics. This can be achieved by applying an id to the specific paragraph. Thus in our CSS we will have:

#italicparagraph { font-style: italic; }

And in our HTML:

<body>
<p> </p>
………
<p id=” italicparagraph”> My italic paragraph </p>
..
<p> </p>
</body>

However, if we want more than one paragraph to displayed in italics, then id should not be used.

That being said, if you try to use id for this propose you will indeed have the desired result. However, your code will not be functional for JavaScript, as we will see later in the course.

There is an alternative selector that is appropriate for this case which is explained in the next section.

Example

The CSS rules:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
        #rainbowColors {background: grey}
        #red {background: red}
        #orange {background: orange}
        #yellow {background: yellow}
        #green {background: green}
        #blue {background: blue}
        #indigo {background: indigo}
        #violet {background: violet}
    </style>
  </head>
  <body>
    <ul id="rainbowColors">
        <li id="red">Red</li>
        <li id="orange">Orange</li>
        <li id="yellow">Yellow</li>
        <li id="green">Green</li>
        <li id="blue">Blue</li>
        <li id="indigo">Indigo</li>
        <li id="violet">Violet</li>
    </ul>
  </body>
</html>


will create a page displayed as:

id selector

Exercise

  1. Open your editor, create a new file and save it as exersice04.1.01.html in the folder "Exercises".
  2. Copy the above code and paste it in the new file.
  3. Modify and save the file. The browser's output should be as shown in the following image:

id selector

Solution: