Class and ID in CSS

nei fogli di stile. Here are some brief tips on how to use class and id in style sheets. Keep in mind that once the use of advanced JavaScript techniques, such as the use of Ajax engines, may come into conflict with the advice given here! And in the end we will see why.

per legare un TAG ad uno stile, spesso si rimane confusi e non si capisce quale sia la differenza o, comunque, la scelta migliore tra i due. With the availability of both the attribute class="" that the attribute id="" to bind to a TAG style, is often confused and do not understand what the difference or at least, the best choice between the two. Truly a tag marked with the class or using the ' id for the CSS does not change anything, or almost. What changes is the way we think about the page and make correct use of id and then find ourselves with no classes to repent of the choices made.

A note on inheritance

Before starting I would like to take this opportunity to emphasize an important behavior, styles, or coscading or inheritance. In practice, a sub-element inherits the characteristics of the parent, unless you explicitly specify that it is !important . Let's see an example that may clarify this situational. Imagine that you have created the following stylesheet:

1
2
font-size : 14px } A_box # p {font-size: 14px}
font-size : 22px } B_box # p {font-size: 22px}

and the following HTML code:

1
2
3
4
5
6
"a_box" > < div id = "a_box">
p > < p > First text directly below a_box </ p >
"b_box" > < div id = "b_box">
p > < p > In the text below b_box and his face under a_box </ p >
</ div >
</ div >

As a result, the browser will actually be the desired one, the first paragraph will be made with the font 14 pixels and the second paragraph with the font to 22 pixels! Let us now try to use class instead of id:

1
2
font-size : 14px } C_box # p {font-size: 14px}
font-size : 22px } . D_box p {font-size: 22px}

HTML code:

1
2
3
4
5
6
"c_box" > < div id = "c_box">
p > < p > First text directly below c_box </ p >
"d_box" > < div class = "d_box">
p > < p > In the text below d_box and his face under c_box </ p >
</ div >
</ div >

The result on the browser (tested on IE6 and Firefox 1.5 +), this time will be different! What happened? ha ereditato il font-size del primo div con id c_box . The div with class d_box inherited font-size of the first div with id c_box . A id , therefore, requires the classes "daughters" to inherit their attributes (although this does not apply to all styles). nella classe d_box , come mostrato qui sotto: To eliminate the problem must be made ​​explicit, with the keywork !important , the font-size class d_box , as shown below:

1
2
font-size : 14px } C_box # p {font-size: 14px}
font-size : 22px !important } . D_box p {font-size: 22px! Important}

In this way we impose to take into account the new style defined with the class d_box .

Using only the classes:

1
2
font-size : 14px } . C_box p {font-size: 14px}
font-size : 22px } . D_box p {font-size: 22px}

HTML code:

1
2
3
4
5
6
"c_box" > < div class = "c_box">
p > < p > First text directly below c_box </ p >
"d_box" > < div class = "d_box">
p > < p > In the text below d_box and his face under c_box </ p >
</ div >
</ div >

The result will be to start the browser, both paragraphs will be rendered correctly. Moral: so careful when using cascading style ... if it is true that there is no immediate difference between classes and id 's also true that their use is not completely identical. Otherwise, why are there two ways of addressing?

Rule

However, there is a way to know who "wins" when you set a style. This technique is usually called Cascade Rule 3.
It provides a value to each selector, or line CSS declarations. This value is in the form ABC.

1) add 1 to A for each id in the selector
2) add 1 to B for each class in the selector
3) add 1 to C for each tag in the selector

Here's an example:

1
2
3
4
5
6
- 1 = 1 - [ p { color : red } 0 - 0 - 1 = 1 - [p {color: red}
- 1 = 11 - [ p .largetext 0 - 1 - 1 = 11 - [p. Largetext
- 1 = 101 - [ p #largetext 1 - 0 - 1 = 101 - [p # largetext
- 2 = 102 - [ body p #largetext 1 - 0 - 2 = 102 - [# body p largetext
- 3 = 113 - [ body p #largetext ul .mylist 1 - 1 - 3 = 113 - [# body p largetext ul. Mylist
- 4 = 114 - [ body p #largetext ul .mylist li 1 - 1 - 4 = 114 - [# body p largetext ul. Mylist them

The highest value wins. If two rules have the same weight to win the last set.

Advice

A road may be this: use the class when the visual behavior of a TAG can vary depending on its parent container. Use id when the visual behavior is unique, that is independent from its parent container.

An illustrative example of this approach could be the following: the behavior of a hypothetical title. In this case we will use the class="title" based on the upper container and adjust behaviors. The CSS file could be:

1
2
3
. ...... {Title }
# ListProducts. Title {........ }
# ListUsers. Title {....... }

In fact, even, things are even better because we have the TAG H<em>n</em> to help us. In a real case the class title would be useless. In practice, the technique is to use the id as selectors of behavior (in fact, are often referred to as id-selector). A real situation could therefore be:

1
2
3
h1 {...... }
H1 {# listProducts ........ }
H1 {# listUsers ....... }

We have three different behaviors depending on the switch. The main rule might be: If this tag will behave differently depending visually using the container class !

In this series, among other things, includes many elements of visual layout such as lists ul . These can result in a different way depending on the container mother can look in the navigation bar, another on the main page, and another in the sidebar, etc. ... But what we need, in most cases, is the only switch id , using the best available standard HTML tag.

quando si può, i TAG titolo H<em>n</em> , i TAG strong , acronym , code , insomma limitare div e span altrimenti rendiamo inutile l'uso degli stili, inondando inoltre la rete con bit supeflui. For example, it is good practice to use lists ul or ol when you can, the title tag H<em>n</em> , the TAG strong , acronym , code , limit short div and span otherwise make unnecessary the use of styles, also flooding the network with bit supeflui. Often, you do not even know all the HTML tags. Some web designers seem to ignore some of the most useful tag in the current HTML standard. Certainly some of TAG (as well as some attributes, events, styles, and, alas, various other little things ...) are confined to the standard of some specific browser, but there are many TAG fully supported by virtually all existing browsers (including Safari - apropos, but Apple has he forgotten that it has developed its own browser?).

Style sheets, still, alas, are also subject to some misunderstanding scattered here and there. Web Designer to do is wait and hope for a future more standard and less variable. Use the id as selectors, therefore, can not refrain from being too involved in a side-effect associated with the use of Javascript. Through the language most widely used client-side, if it is enabled in your browser, you can get a pointer to a specific page element or tag. . This is now solved with ease (some time ago was slightly more complex, due to the ever present incompatibility between browsers!) Via the getElementByID() made ​​available by the object document .

dell'elemento. As can be seen by the same method name, getElementByID() retrieves the pointer on the basis of ' id of the element. per rintracciare l'elemento. The problem has to do with style sheets is that the ' id in question is exactly the same used by getElementByID() to track the item. So imagine having to write a web application that manages a series of post-it on the screen, if anything with the position:absolute on. This means that post-it notes on the page it could have an unspecified number of n. . The Web designer who wants to write the style sheet for this object, following our previous rule would choose to use a div container and give it an id="postIt" . In this way we would follow the rule when a post-it does not behave itself in a visually different depending on the parent container. In our specification it is an object is unique and therefore properly associate an ' id . The trouble comes when the JavaScript programmer (the characters of this MiniStore are 2 different, but the question would still embarrassing ... even for a single developer) attempts to obtain a pointer to a specific post-it! It quickly realizes that he can not use the ID as a discriminator in that if there are more elements on the page with the same ID then getElementByID() can not return a single pointer, the limit can return a list (array), a list of all elements that are called the same way.

This long and tedious discussion brings with it a note accordingly. In developing HTML / JavaScript / CSS and style sheets in particular, much depends on the overall vision. There is indeed a rule that applies to any solution. Being able to see the project in its entirety can help more of the rules stated.

3 comments to "Classes and ID in CSS"

  1. July 1, 2008 GPJ:

    But that good! You explain very well :)

  2. July 1, 2008 Giovambattista Fazioli :

    @ GPJ: thanks! To ask questions or contact me ;)

  3. November 10, 2008 Very short trick: versatility of CSS classes | Undolog.com :

    [...] In the CSS. An overview of some differences and warnings can be found on the Class and ID in CSS, however, a useful feature that distinguishes class id, is the ability to use classes [...]

Leave a comment

XHTML TAG PERMIT: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERTION CODE:
 <pre></pre> // blocco generico <code></code> // blocco generico [cc_actionscript][/cc_actionscript] // Actionscript [cc_actionscript3][/cc_actionscript3] // Actionscript 3 [cc_css][/cc_css] // CSS Style Sheet [cc_html][/cc_html] // HTML [cc_js][/cc_js] // Javascript [cc_objc][/cc_objc] // Objective-C [cc_php][/cc_objc] // PHP [cc_sql][/cc_sql] // SQL