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
class
andid
are global attributes, and may therefore be assigned to any HTML element. - Class names must begin with a letter (A-Z or a-z) and can be followed by letters, digits , hyphens and underscores.
- In
HTML5
, the class and id attributes can be used on any element. In HTML 4.0.1, they were off-limits to the<base>
,<head>
,<html>
,<meta>
,<param>
,<script>
,<style>
and<title>
tags. - 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