can I apply IDs more than once in CSS?

css, html, xhtml

Solution

ID's are meant to use for identifying elements uniquely, they will work as far as CSS goes, but when JavaScript comes into action, you will understand why not to do so.

CSS just selects the element, when you write a matching selector, it has nothing to do with valid or invalid HTML you write, the job of CSS is to apply styles as per the selector defined. For example

Demo INVALID HTML, DO NOT USE IT (only for demonstration purpose)

Hence, `ID`'s should be unique,, use `class` if you want to use the same properties on multiple elements.

From W3C

This attribute assigns a name to an element. This name must be unique in a document.

Side tip: Use `_` instead of spaces `href="ID & Classes.css"` should be `href="IDs_Classes.css"`.

Here's a good read, on why not to do that (So won't repeat here)

Problem

This is a beginner's question, but I need to clarify it. Yes according to most of the tutorials it cannot be applied more than once. ID's are unique Each element can have only one ID Each page can have only one element with that ID Reference http://css-tricks.com/the-difference-between-id-and-class/ But I wrote a simple mark-up in HTML and applied some CSS. Here is my code HTML ``` <!DOCTYPE html> <html> <head> <title>ID vs Classes</title> <link rel="stylesheet" type="text/css" href="ID & Classes.css"> </head> <body> <h1 id="forh1">This is a h1 header</h1> <p>Lorem ipsum dolor sit amet</p> <h1 id="forh1">This is a h1 header</h1> <p>Curabitur sodales ligula</p> <h2 id="forh1">This is a h2 header</h2> </body> </html> ``` CSS ``` #forh1{ text-align:center; } ``` I have applied the same ID more than once (3 times). Two times in h1 header and one time in h2 header. When I run it in browser (chrome & firefox) they worked perfectly. All text in h1 and h2 headers were aligned center. Why is that ? Have not I grasped ID concept properly or is it an issue with the browser? Because I have heard modern browsers are smart enough to understand most of the implicit things. Please help.

Original source