Stats

531 Contributors: 28 Thursday, December 29, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Classes and IDs

Introduction

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

ParameterDetails
classIndicates the Class of the element (non-unique)
idIndicates the ID of the element (unique in the same context)

Remarks

  • Both class and id 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.

Related Examples