ID - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

21
ID

At this point you should be clear about CSS classes. They can be tied to an element, like this.

p.extra-special {
font-style: italic;
}

Or they can be for general use—that is, not tied to any particular element, like this.

.extra-special {
font-style: italic;
}

In HTML you assign a class to an element like this.

<p class="extra-special">Daily Special<p/>

A class can be assigned to any number of elements. And an element can be assigned any number of classes. If you have a paragraph class, it can be assigned to a thousand different paragraphs if you like. If you have a class that isn’t tied to a particular element, it can be assigned to different kinds of elements.

An id is like a class, but more exclusive. It can be assigned only once in an HTML document. And an element, though it can have many classes, can have only one id.

For example, suppose you’re styling a paragraph that contains a mission statement. This particular styling won’t be used for any other paragraph. You could style this special paragraph with a class, but it would be clearer, from a human point of view, to single it out as unique by assigning it an id.

The following code creates an id and styling for the mission statement.

p#mission-statement {
font-family: "Times New Roman", Times, serif;
font-size: 1.2em;
color: darkblue;
}

Note that in the CSS the syntax you use to define ids is exactly the same as for classes, except that a # replaces the dot.

The following code creates a heading id.

The following code creates an id that can be used for a paragraph, a heading, or other elements that you’ll learn about later. But remember, any id, including this one, should be used only once on any HTML page. For example, if you use it for a paragraph, don’t use it for another paragraph, a heading, or any other element on the page.

#special {
font-size: 1.5em;
font-style: italic;
}

Here’s an example of HTML that assigns an id to an element.

<p id="whatever">This paragraph has a unique id.</p>

In the HTML the syntax is exactly the same, except that you replace class with id.

ids are important in HTML, but they play an even larger role in JavaScript, as you’ll learn in my book A Smarter Way to Learn JavaScript, available at Amazon.

In your CSS file code an h2 id that colors the heading orange. In your HTML file code a heading with that id. Save the files. Display the page.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-21-1.html.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-21-2.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/21.html