When to use CSS ids and when CSS classes instead?
At first glance, the use of classes and ids is almost identical: both can assign CSS properties with needed values to change the appearance of HTML document. But, under what circumstances can we make better use of classes, and under what ids?
The most important rule of using classes and identifiers is that the identifier can only be used once in a document, because it works only with one element. If assigned to an element this unique identifier can no longer be used in the same document.
Classes, on contrary, can be used in a document any number of times. Therefore, if multiple elements have the same properties on the same page, use of the classes can be considered as an ideal solution.
As a rule, identifier is assigned to the most important elements that have an essential role in shaping the structure of the document. Thus, the more common identifiers are: header, content, nav and footer. Below is code example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB" lang="en-GB"> <head> <title>Simple site</title> <meta name="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> <div id="header"> ... </div> <div id="content"> ... the content of the page ... </div> <div id="nav"> ... </div> <div id="footer"> ... </div> </body> </html>