Классы

Содержание
  1. Browser Support
  2. Syntax
  3. Attribute Values
  4. More Examples
  5. Example
  6. Header 1 A paragraph.
  7. Example
  8. Example
  9. Related Pages
  10. COLOR PICKER
  11. Report Error
  12. Thank You For Helping Us!
  13. HTML class Attribute
  14. Using The class Attribute
  15. Example
  16. London
  17. Paris
  18. Tokyo
  19. Example
  20. My Important Heading
  21. The Syntax For Class
  22. Example
  23. Multiple Classes
  24. Example
  25. London
  26. 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 Источник Классы Классы применяют, когда необходимо определить стиль для индивидуального элемента веб-страницы или задать разные стили для одного тега. При использовании совместно с тегами синтаксис для классов будет следующий. Внутри стиля вначале пишется желаемый тег, а затем, через точку пользовательское имя класса. Имена классов должны начинаться с латинского символа и могут содержать в себе символ дефиса (-) и подчеркивания (_). Использование русских букв в именах классов недопустимо. Чтобы указать в коде 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. Какое имя класса следует добавить к тегу , чтобы текст был одновременно жирным и красного цвета, если имеется следующий стиль? Источник How to define and use a class in CSS? I’ve almost never coded in CSS before, and I saw this in the power point of my web development class (it’s originally written in French so I’m not sure if my translation is completely accurate): The with the property and inside the element will have the following CSS properties: td p .indented this is the body of the document
    td p .indented td
    1 2 3

    test

    test
    all 3 test are displayed in purple, but nothing is displaying in red and bold text. Am I doing something wrong? Thanks First, you should have class=»indented» with the quotation marks, second td p .indented isn’t the same as td p.indented . In your example, you’re targeting an element with the class indented inside a p, not a p with the class indented. 5 Answers 5 You have a slight typo in your CSS rule. td p .indented targets elements with the class indented that are descendants of a p elements, which in turn is a descendant of a td element. What you’re likely looking for is to target p elements with the class indented which are children of a td element. Remove the whitespace between p and .indented in your selector definition: this is the body of the document
    td p.indented td
    1 2 3

    test

    test
    You can write CSS in 3 ways : internal CSS written as a style=»» attribute right beside the other attributes of your tag Another way is by embedded stylesheets method which you have opted in you code, giving section of the document. Here, the only flaw is: that you have given a space between p and .indented due to which it is read as if contains a child element to which .indented class has been applied, whereas you wanted to apply the class to itself and access it. And, the third way is external stylesheets that is maintaining the styles in a separate file other than the html file. So, the following code will fix the problem for you. All the best! this is the body of the document
    td p.indented td
    1 2 3

    test

    test
    You are quite there with your code, there is only a minor typing flaw td p .indented needs to be td p.indented as it changes the whole meaning of CSS descendants selector theory. Use , . Your code should be like this is the body of the document
    td, p.indented td
    1 2 3

    test

    test
    I don’t believe this is what the OP was intending. This will make all td , p , and .indented elements bold and red. To define a class in HTML tags you’ll have to use this type of syntax: class = «classname» So try changing the class=indented to class = «indented» Источник
  27. 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 Источник Классы Классы применяют, когда необходимо определить стиль для индивидуального элемента веб-страницы или задать разные стили для одного тега. При использовании совместно с тегами синтаксис для классов будет следующий. Внутри стиля вначале пишется желаемый тег, а затем, через точку пользовательское имя класса. Имена классов должны начинаться с латинского символа и могут содержать в себе символ дефиса (-) и подчеркивания (_). Использование русских букв в именах классов недопустимо. Чтобы указать в коде 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. Какое имя класса следует добавить к тегу , чтобы текст был одновременно жирным и красного цвета, если имеется следующий стиль? Источник How to define and use a class in CSS? I’ve almost never coded in CSS before, and I saw this in the power point of my web development class (it’s originally written in French so I’m not sure if my translation is completely accurate): The with the property and inside the element will have the following CSS properties: td p .indented this is the body of the document
    td p .indented td
    1 2 3

    test

    test
    all 3 test are displayed in purple, but nothing is displaying in red and bold text. Am I doing something wrong? Thanks First, you should have class=»indented» with the quotation marks, second td p .indented isn’t the same as td p.indented . In your example, you’re targeting an element with the class indented inside a p, not a p with the class indented. 5 Answers 5 You have a slight typo in your CSS rule. td p .indented targets elements with the class indented that are descendants of a p elements, which in turn is a descendant of a td element. What you’re likely looking for is to target p elements with the class indented which are children of a td element. Remove the whitespace between p and .indented in your selector definition: this is the body of the document
    td p.indented td
    1 2 3

    test

    test
    You can write CSS in 3 ways : internal CSS written as a style=»» attribute right beside the other attributes of your tag Another way is by embedded stylesheets method which you have opted in you code, giving section of the document. Here, the only flaw is: that you have given a space between p and .indented due to which it is read as if contains a child element to which .indented class has been applied, whereas you wanted to apply the class to itself and access it. And, the third way is external stylesheets that is maintaining the styles in a separate file other than the html file. So, the following code will fix the problem for you. All the best! this is the body of the document
    td p.indented td
    1 2 3

    test

    test
    You are quite there with your code, there is only a minor typing flaw td p .indented needs to be td p.indented as it changes the whole meaning of CSS descendants selector theory. Use , . Your code should be like this is the body of the document
    td, p.indented td
    1 2 3

    test

    test
    I don’t believe this is what the OP was intending. This will make all td , p , and .indented elements bold and red. To define a class in HTML tags you’ll have to use this type of syntax: class = «classname» So try changing the class=indented to class = «indented» Источник
  28. Different Elements Can Share Same Class
  29. Example
  30. Use of The class Attribute in JavaScript
  31. Example
  32. Chapter Summary
  33. Классы
  34. Одновременное использование разных классов
  35. Вопросы для проверки
  36. How to define and use a class in CSS?
  37. 5 Answers 5

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 >

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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 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 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

Источник

Классы

Классы применяют, когда необходимо определить стиль для индивидуального элемента веб-страницы или задать разные стили для одного тега. При использовании совместно с тегами синтаксис для классов будет следующий.

Внутри стиля вначале пишется желаемый тег, а затем, через точку пользовательское имя класса. Имена классов должны начинаться с латинского символа и могут содержать в себе символ дефиса (-) и подчеркивания (_). Использование русских букв в именах классов недопустимо. Чтобы указать в коде 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. Какое имя класса следует добавить к тегу , чтобы текст был одновременно жирным и красного цвета, если имеется следующий стиль?

Источник

How to define and use a class in CSS?

I’ve almost never coded in CSS before, and I saw this in the power point of my web development class (it’s originally written in French so I’m not sure if my translation is completely accurate):

The 

with the property and inside the element will have the following CSS properties: td p .indented

  this is the body of the document 
td p .indented td
1 2 3

test

test

all 3 test are displayed in purple, but nothing is displaying in red and bold text. Am I doing something wrong? Thanks

First, you should have class=»indented» with the quotation marks, second td p .indented isn’t the same as td p.indented . In your example, you’re targeting an element with the class indented inside a p, not a p with the class indented.

5 Answers 5

You have a slight typo in your CSS rule. td p .indented targets elements with the class indented that are descendants of a p elements, which in turn is a descendant of a td element.

What you’re likely looking for is to target p elements with the class indented which are children of a td element. Remove the whitespace between p and .indented in your selector definition:

  this is the body of the document 
td p.indented td
1 2 3

test

test

You can write CSS in 3 ways : internal CSS written as a style=»» attribute right beside the other attributes of your

tag Another way is by embedded stylesheets method which you have opted in you code, giving section of the document. Here, the only flaw is: that you have given a space between p and .indented due to which it is read as if

contains a child element to which .indented class has been applied, whereas you wanted to apply the class to

itself and access it. And, the third way is external stylesheets that is maintaining the styles in a separate file other than the html file. So, the following code will fix the problem for you. All the best!

 this is the body of the document 
td p.indented td
1 2 3

test

test

You are quite there with your code, there is only a minor typing flaw td p .indented needs to be td p.indented as it changes the whole meaning of CSS descendants selector theory.

Use , . Your code should be like

 this is the body of the document 
td, p.indented td
1 2 3

test

test

I don’t believe this is what the OP was intending. This will make all td , p , and .indented elements bold and red.

To define a class in HTML tags you’ll have to use this type of syntax: class = «classname»

So try changing the class=indented to class = «indented»

Источник

Читайте также:  Способы выполнять код параллельно асинхронно python

Оцените статью