- Классы
- Одновременное использование разных классов
- Вопросы для проверки
- Browser Support
- Syntax
- Attribute Values
- More Examples
- Example
- Header 1 A paragraph.
- Example
- Example
- Related Pages
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- HTML Class Attribute
- Syntax
- Example of the HTML class attribute used with CSS:
- Example of the HTML class attribute with multiple class names:
- Example of the HTML class attribute with the and elements:
- HTML class Attribute
- Using The class Attribute
- Example
- London
- Paris
- Tokyo
- Example
- My Important Heading
- The Syntax For Class
- Example
- Multiple Classes
- Example
- London
- Different Elements Can Share Same Class Different HTML elements can point to the same class name. In the following example, both and point to the «city» class and will share the same style: Example Use of The class Attribute in JavaScript The class name can also be used by JavaScript to perform certain tasks for specific elements. JavaScript can access elements with a specific class name with the getElementsByClassName() method: Example Click on a button to hide all elements with the class name «city»: Don’t worry if you don’t understand the code in the example above. You will learn more about JavaScript in our HTML JavaScript chapter, or you can study our JavaScript Tutorial. Chapter Summary The HTML class attribute specifies one or more class names for an element Classes are used by CSS and JavaScript to select and access specific elements The class attribute can be used on any HTML element The class name is case sensitive Different HTML elements can point to the same class name JavaScript can access elements with a specific class name with the getElementsByClassName() method Источник
- Different Elements Can Share Same Class Different HTML elements can point to the same class name. In the following example, both and point to the «city» class and will share the same style: Example Use of The class Attribute in JavaScript The class name can also be used by JavaScript to perform certain tasks for specific elements. JavaScript can access elements with a specific class name with the getElementsByClassName() method: Example Click on a button to hide all elements with the class name «city»: Don’t worry if you don’t understand the code in the example above. You will learn more about JavaScript in our HTML JavaScript chapter, or you can study our JavaScript Tutorial. Chapter Summary The HTML class attribute specifies one or more class names for an element Classes are used by CSS and JavaScript to select and access specific elements The class attribute can be used on any HTML element The class name is case sensitive Different HTML elements can point to the same class name JavaScript can access elements with a specific class name with the getElementsByClassName() method Источник
- Different Elements Can Share Same Class
- Example
- Use of The class Attribute in JavaScript
- Example
- Chapter Summary
Классы
Классы применяют, когда необходимо определить стиль для индивидуального элемента веб-страницы или задать разные стили для одного тега. При использовании совместно с тегами синтаксис для классов будет следующий.
Внутри стиля вначале пишется желаемый тег, а затем, через точку пользовательское имя класса. Имена классов должны начинаться с латинского символа и могут содержать в себе символ дефиса (-) и подчеркивания (_). Использование русских букв в именах классов недопустимо. Чтобы указать в коде HTML, что тег используется с определённым классом, к тегу добавляется атрибут class=»Имя класса» (пример 8.1).
Пример 8.1. Использование классов
HTML5 CSS 2.1 IE Cr Op Sa Fx
Для искусственного освещения помещения применяются люминесцентные лампы. Они отличаются высокой световой отдачей, продолжительным сроком службы, малой яркостью светящейся поверхности, близким к естественному спектральным составом излучаемого света, что обеспечивает хорошую цветопередачу.
Результат данного примера показан на рис. 8.1.
Рис. 8.1. Вид текста, оформленного с помощью стилевых классов
Первый абзац выровнен по ширине с текстом чёрного цвета (этот цвет задаётся браузером по умолчанию), а следующий, к которому применен класс с именем cite — отображается синим цветом и с линией слева.
Можно, также, использовать классы и без указания тега. Синтаксис в этом случае будет следующий.
При такой записи класс можно применять к любому тегу (пример 8.2).
Пример 8.2. Использование классов
HTML5 CSS 2.1 IE Cr Op Sa Fx
Согласно , шумовой характеристикой рабочих мест при постоянном шуме являются уровни звуковых давлений в децибелах в октавных полосах. Совокупность таких уровней называется , номер которого численно равен уровню звукового давления в октавной полосе со среднегеометрической частотой 1000 Гц.
Результат применения классов к тегам и показан на рис. 8.2.
Рис. 8.2. Вид тегов, оформленных с помощью классов
Классы удобно использовать, когда нужно применить стиль к разным элементам веб-страницы: ячейкам таблицы, ссылкам, абзацам и др. В примере 8.3 показано изменение цвета фона строк таблицы для создания «зебры».
Пример 8.3. Использование классов
HTML5 CSS 2.1 IE Cr Op Sa Fx
Название Цвет Твердость по Моосу АлмазБелый 10 Рубин Красный 9 АметистГолубой 7 Изумруд Зеленый 8 СапфирГолубой 9
Рис. 8.3. Результат применения классов
Одновременное использование разных классов
К любому тегу одновременно можно добавить несколько классов, перечисляя их в атрибуте class через пробел. В этом случае к элементу применяется стиль, описанный в правилах для каждого класса. Поскольку при добавлении нескольких классов они могут содержать одинаковые стилевые свойства, но с разными значениями, то берётся значение у класса, который описан в коде ниже.
В примере 8.4 показано использование разных классов для создания облака тегов.
Пример 8.4. Сочетание разных классов
HTML5 CSS 2.1 IE Cr Op Sa Fx
Paint.NET Photoshop цвет фон палитра слои свет панели линия прямоугольник пиксел градиент
Результат данного примера показан на рис. 8.4.
В стилях также допускается использовать запись вида .layer1.layer2 , где layer1 и layer2 представляют собой имена классов. Стиль применяется только для элементов, у которых одновременно заданы классы layer1 и layer2 .
Вопросы для проверки
1. Какое имя класса написано правильно?
2. Какой цвет будет у слова «потока» в коде?
При использовании следующего стиля?
4. Какое имя класса следует добавить к тегу , чтобы текст был одновременно жирным и красного цвета, если имеется следующий стиль?
A paragraph.
The class attribute specifies one or more class names for an element.
The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.
Browser Support
Syntax
Attribute Values
Value | Description |
---|---|
classname | Specifies one or more class names for an element. To specify multiple classes, separate the class names with a space, e.g. . This allows you to combine several CSS classes for one HTML element. |
- Must begin with a letter A-Z or a-z
- Can be followed by: letters (A-Za-z), digits (0-9), hyphens («-«), and underscores («_»)
More Examples
Example
Add multiple classes to one HTML element:
Header 1
A paragraph.
Example
Using JavaScript to add a yellow background color to the first element with class=»example» (index 0).
Example
Using JavaScript to add the «mystyle» class to an element with >
Related Pages
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
HTML Class Attribute
The HTML class attribute is used to specify one or more class names for an element. Commonly, the class attribute points to a class in a style sheet. The class name is case sensitive.
This attribute can also be used by JavaScript via the HTML DOM to make certain changes to HTML elements with a specified class name.
In HTML5, you can use the class attribute for any HTML element.
In HTML 4.01, the class attribute cannot be used with the following elements: , , , , , , , , and .
Although there aren’t specific requirements for the name of classes, it’s better to use names describing the semantic purpose of the element, and not its presentation. The name should begin with a letter a-z or A-Z, and it can be followed by letters, digits (0-9), underscores («_»), and hyphens («-«).
Syntax
html> html> head> title>Title of the document title> style> .red < color: red; > .orange < color: orange; > style> head> body> h1>Example of the HTML class attribute h1> p class="red">It is a some red paragraph. p> p>This is a some text. p> p class="orange">It is a some yellow paragraph. p> body> html>
In CSS, if you want to select elements with a specific class, use a period (.) character followed by the class name.
Example of the HTML class attribute used with CSS:
html> html> head> title>Title of the document title> style> .title < background-color: #1c87c9; color: #ffffff; padding: 20px; > style> head> body> h1>Example of the class attribute h1> h2 class="title">Heading h2> p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> h2 class="title">Heading h2> p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
HTML elements can also have more than one class name. Each of them must be separated by a space.
Example of the HTML class attribute with multiple class names:
html> html> head> title>Title of the document title> style> .title < background-color: #202131; color: #dddddd; padding: 15px 25px; > .text-right < text-align: right; > style> body> h1>Example of multiple classes h1> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> h2 class="title">London h2> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> h2 class="title text-right">Paris h2> p> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> h2 class="title">Tokyo h2> body> html>
Example of the HTML class attribute with the and
elements:
html> html> head> title>Title of the document title> style> .grey-text < color: #808080; > style> body> h1>Example of the class attribute h1> h2 class="grey-text">Heading h2> p class="grey-text"> Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. p> body> html>
HTML class Attribute
The HTML class attribute is used to specify a class for an HTML element.
Multiple HTML elements can share the same class.
Using The class Attribute
The class attribute is often used to point to a class name in a style sheet. It can also be used by a JavaScript to access and manipulate elements with the specific class name.
In the following example we have three elements with a class attribute with the value of «city». All of the three elements will be styled equally according to the .city style definition in the head section:
Example
London
London is the capital of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
In the following example we have two elements with a class attribute with the value of «note». Both elements will be styled equally according to the .note style definition in the head section:
Example
My Important Heading
This is some important text.
Tip: The class attribute can be used on any HTML element.
Note: The class name is case sensitive!
Tip: You can learn much more about CSS in our CSS Tutorial.
The Syntax For Class
To create a class; write a period (.) character, followed by a class name. Then, define the CSS properties within curly braces <>:
Example
Create a class named «city»:
London is the capital of England.
Paris is the capital of France.
Tokyo is the capital of Japan.
Multiple Classes
HTML elements can belong to more than one class.
To define multiple classes, separate the class names with a space, e.g. . The element will be styled according to all the classes specified.
In the following example, the first element belongs to both the city class and also to the main class, and will get the CSS styles from both of the classes:
Example
London
Different Elements Can Share Same Class
Different Elements Can Share Same Class
Different HTML elements can point to the same class name.
In the following example, both and
point to the «city» class and will share the same style:
Example
Use of The class Attribute in JavaScript
The class name can also be used by JavaScript to perform certain tasks for specific elements.
JavaScript can access elements with a specific class name with the getElementsByClassName() method:
Example
Click on a button to hide all elements with the class name «city»:
Don’t worry if you don’t understand the code in the example above.
You will learn more about JavaScript in our HTML JavaScript chapter, or you can study our JavaScript Tutorial.
Chapter Summary
- The HTML class attribute specifies one or more class names for an element
- Classes are used by CSS and JavaScript to select and access specific elements
- The class attribute can be used on any HTML element
- The class name is case sensitive
- Different HTML elements can point to the same class name
- JavaScript can access elements with a specific class name with the getElementsByClassName() method