Classes and IDs
suggest changeIntroduction
Classes and IDs make referencing HTML elements from scripts and stylesheets easier. The class attribute can be used on one or more tags and is used by CSS for styling. IDs however are intended to refer to a single element, meaning the same ID should never be used twice. IDs are generally used with JavaScript and internal document links, and are discouraged in CSS. This topic contains helpful explanations and examples regarding proper usage of class and ID attributes in HTML.
Syntax
- class=“class1 class2 class3”
- id=“uniqueid”
Parameters
Parameter| Details|
|–––––|––––| | class | Indicates the Class of the element (non-unique) | | id | Indicates the ID of the element (unique in the same context) |
Remarks
- Both
classandidare global attributes, and may therefore be assigned to any HTML element. - In HTML 4.01, class and id tokens must begin with a letter (A-Z or a-z) and can be followed by letters, digits, hyphens, underscores, colons, and periods. HTML5 allows many more characters (no ASCII whitespace), but values that are awkward in CSS or JavaScript are still a bad idea. See Acceptable Values.
- In HTML5, the
classandidattributes can be used on any element. In HTML 4.01, they were not allowed on the<base>,<head>,<html>,<meta>,<param>,<script>,<style>, and<title>elements. - An element can have one or more classes. Classes are separated by spaces and cannot contain spaces themselves.
- An element can have only one ID and it must be unique within its context (i.e. a webpage). IDs also cannot contain spaces themselves.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents