HTML naming conventions for ID, class and to include element type prefix?

Viewed 43422

Does anyone know of a good resource to explain good naming conventions for HTML ID and classes and whether to prefix with IDs with an element type i.e. btn or button or similar?

Should classes be plural or singular? I get that IDs should be singular due to them being unique, but what about classes?

IDs and classes should use nouns, right?

I am using pages that inject other pages in the existing pages, kind of like partial pages ... hence... I was wondering if anybody as prefixed a name in front of IDs and/or classes .. kind of like a namespace or similar?

Any comments or insights really appreciated.

3 Answers

A lot of people don't realize you can do this stuff:

.awesome {
 /* rules for anything awesome */
}

div.awesome {
 /* rules for only awesome divs */
}

button.awesome {
 /* rules for any awesome buttons, but not awesome divs */
}

div.awesome h1 {
 /* rules for H1s inside of any div.awesome */
}

div.awesome>button {
 /* rules for immediate children buttons (not grandchildren+) of div.awesomes */
}

I wouldn't prefix with the type, as you can infer this in the selector if you must

form#contact {
    property: value;

}

The method you described is known as Hungarian notation, and isn't very popular.

For what you mention, you could place your injected HTML inside one div with one unique class/id, which has a sort of localised reset. Look up CSS selector specificty to ensure your rules will take affect and not other rules in the host page's CSS. See this answer to a similar question regarding styling an element within a parent page.

Related