Атрибут class в HTML
Атрибут class в HTML используется для указания одного или нескольких имён классов для элемента. Обычно атрибут class ссылается на класс в таблице стилей. Имя класса чувствительно к регистру.
Этот атрибут также может использоваться JavaScript через HTML DOM для внесения определённых изменений в HTML-элементы с указанным именем класса.
В HTML5 вы можете использовать атрибут class для любого HTML-элемента.
В HTML 4.01 атрибут class нельзя использовать со следующими элементами: <head>, <html>, <base>, <basefont>, <param>, <style>, <meta>, <script>, и <title>.
Хотя к именам классов не предъявляется строгих требований, лучше использовать имена, описывающие семантическое назначение элемента, а не его внешний вид. Имя должно начинаться с буквы (a-z или A-Z), дефиса (-) или символа подчёркивания (_), и может содержать буквы, цифры (0-9), подчёркивания и дефисы.
Синтаксис
Синтаксис атрибута class в HTML
<tag class="classname"></tag>Пример атрибута class в HTML:
Пример атрибута class в HTML
<!DOCTYPE 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 some red paragraph.</p>
<p>This is a some text.</p>
<p class="orange">It is some orange paragraph.</p>
</body>
</html>В CSS, если вы хотите выбрать элементы с определённым классом, используйте точку (.) перед именем класса.
Пример использования атрибута class в HTML с CSS:
Пример использования атрибута class в HTML с CSS
<!DOCTYPE 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>Вы также можете управлять атрибутом class с помощью JavaScript. Свойство classList предоставляет методы для добавления, удаления или переключения классов в динамическом режиме.
Пример использования атрибута class в HTML с JavaScript:
Пример атрибута class в HTML с JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="demo">Click the button to add a class.</p>
<button onclick="document.getElementById('demo').classList.add('highlight')">Add Class</button>
</body>
</html>HTML-элементы также могут иметь более одного имени класса. Каждое из них должно быть разделено пробелом.
Пример атрибута class в HTML с несколькими именами классов:
Пример атрибута class в HTML с несколькими именами классов
<!DOCTYPE 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>
</head>
<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>Различные теги, такие как <h2> и <p>, могут иметь одинаковое имя класса и одинаковый стиль.
Пример атрибута class в HTML для элементов <h2> и <p>:
Пример атрибута class в HTML
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.grey-text {
color: #808080;
}
</style>
</head>
<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>Практика
Какова цель атрибута class в HTML?