Перейти к содержимому

Чем class отличается от id

  • автор:

Изучаем CSS: class или id – что лучше?

Контролировать внешний вид HTML-элементов на странице можно при помощи нескольких селекторов. ID и CSS class являются наиболее распространенными, которые помогают не только в создании разметки HTML-документов , но и в их оформлении ( стилизации ).

Как применять CSS-селектор ID

Селектор ID используется для обозначения отдельного HTML-элемента с помощью уникального значения атрибута id . В следующем примере представлен элемент <div>, значением атрибута id которого является header .

В CSS к этому div-элементу можно применять различную стилизацию:

Не забывайте использовать знак # ( хэштег ) перед именем. Подробнее об этом можно узнать здесь и здесь .

Как применять CSS-селектор class

Селектор class HTML CSS используется для выделения отдельного или целой группы HTML-элементов с идентичным значением атрибута class .

В CSS к нескольким абзацам можно применять различную стилизацию:

Не забудьте использовать знак . ( точка ) перед названием класса при объявлении CSS-правила . Подробнее об этом можно узнать здесь и здесь .

Чем отличаются CSS Class и ID

Cелектор id используется для отдельных элементов страницы ( #header ), в то время как селектор class (.content) – для нескольких. Так как значение id задается лишь одному HTML-элементу . Другими словами, у нескольких элементов не может быть одинакового значения id в рамках одной отдельной страницы. Например, у вас может быть только один элемент с id #header , или же один элемент с id #footer .

Одинаковое значение class можно задавать одному или нескольким HTML-элементам . К примеру, у вас может быть несколько абзацев с классом .content или несколько ссылок с классом .external .

Следующий пример поможет лучше понять различия между CSS class и id , а также понять, как правильно использовать:

Приведенную выше HTML-разметку мы начали с div-элемента container . Мы задали ему id ( #container ), так как на нашей странице будет размещаться единственный контейнер. Внутри него мы размещаем разделы меню ( #menu ) и контента ( #content ). Как и в случае с контейнером, у нас будет только одно меню, и один раздел с контентом. Внутри menu располагаются четыре ссылки <a>, но к каждой из них мы применили CSS class ( .link ). Точно также мы применили класс ( .text ) к каждому абзацу в div-элементе content .

Если нужно стилизовать эти элементы, то можно использовать следующий пример:

Когда используется class, а когда id?

ID используется для отдельных элементов, которые встречаются на странице только один раз. Например, заголовок, подвал, меню и т. д. Селектор class используется для одного или нескольких элементов, которые встречаются на странице несколько раз. Например, абзацы, ссылки, кнопки, элементы ввода. И хотя вы можете использовать class для отдельного элемента, но лучше использовать эти селекторы по назначению.

Также следует учитывать, что у HTML-элемента может быть указан и id , и class . Предположим, что на странице имеется два блока с одинаковым размером и стилизацией, но с разным позиционированием. В таком случае можно применить один и тот же класс к этим блокам для изменения размеров и стилизации, а затем использовать отдельный ID-селектор к каждому блоку, чтобы задать им разное позиционирование.

Элементы также можно привязывать одновременно к нескольким классам. Это очень удобно, когда нужно применить стилизацию к отдельной группе элементов определенного типа. Например, имеется класс .content , который применен ко всем абзацам. Если нужно будет добавить границу или любую другую стилизацию к нескольким отдельным абзацам, то можно сделать это при помощи дополнительного CSS p class .bordered :

Обратите внимание на пустое пространство между двумя именами классов в атрибуте class второго абзаца. Ниже приведен пример CSS-кода :

Важно правильно применять id и CSS class , так как их неправильное использование может привести к ошибкам в отображении HTML-кода .

# Classes and IDs

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.

# Giving an element a class

Classes are identifiers for the elements that they are assigned to. Use the class attribute to assign a class to an element.

To assign multiple classes to an element, separate the class names with spaces.

# Using classes in CSS

Classes can be used for styling certain elements without changing all elements of that kind. For example, these two span elements can have completely different stylings:

Classes of the same name can be given to any number of elements on a page and they will all receive the styling associated with that class. This will always be true unless you specify the element within the CSS.

For example, we have two elements, both with the class highlight :

If our CSS is as below, then the color green will be applied to the text within both elements:

However, if we only want to target div ‘s with the class highlight then we can add specificity like below:

Nevertheless, when styling with CSS, it is generally recommended that only classes (e.g. .highlight ) be used rather than elements with classes (e.g. div.highlight ).

As with any other selector, classes can can be nested:

You can also chain the class selector to only select elements that have a combination of several classes. For example, if this is our HTML:

And we want to colour this specific piece of text pink, we can do the following in our CSS:

# Giving an element an ID

The ID attribute of an element is an identifier which must be unique in the whole document. Its purpose is to uniquely identify the element when linking (using an anchor), scripting, or styling (with CSS).

You should not have two elements with the same ID in the same document, even if the attributes are attached to two different kinds of elements. For example, the following code is incorrect:

Browsers will do their best to render this code, but unexpected behavior may occur when styling with CSS or adding functionality with JavaScript.

To reference elements by their ID in CSS, prefix the ID with # .

To jump to an element with an ID on a given page, append # with the element name in the URL.

This feature is supported in most browsers and does not require additional JavaScript or CSS to work.

# Acceptable Values

# For an ID

The only restrictions on the value of an id are:

  1. it must be unique in the document
  2. it must not contain any space characters
  3. it must contain at least one character

So the value can be all digits, just one digit, just punctuation characters, include special characters, whatever. Just no whitespace.

So these are valid:

This is invalid:

This is also invalid, when included in the same document:

An id value must begin with a letter, which can then be followed only by:

  • letters (A-Z/a-z)
  • digits (0-9)
  • hyphens ("-")
  • underscores ("_")
  • colons ("��
  • periods (".")

Referring to the first group of examples in the HTML5 section above, only one is valid:

These are also valid:

Again, if it doesn’t start with a letter (uppercase or lowercase), it’s not valid.

# For a Class

The rules for classes are essentially the same as for an id . The difference is that class values do not need to be unique in the document.

Referring to the examples above, although this is not valid in the same document:

This is perfectly okay:

# Important Note: How ID and Class values are treated outside of HTML

Keep in mind that the rules and examples above apply within the context of HTML.

Using numbers, punctuation or special characters in the value of an id or a class may cause trouble in other contexts, such as CSS, JavaScript and regular expressions.

For example, although the following id is valid in HTML5:

. it is invalid in CSS:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. (emphasis added)

In most cases you may be able to escape characters in contexts where they have restrictions or special meaning.

# W3C References

# Problems related to duplicated IDs

Having more than one element with the same ID is a hard to troubleshoot problem. The HTML parser will usually try to render the page in any case. Usually no error occurs. But the pace could end up in a mis-behaving web page.

In this example:

CSS selectors still work

But JavaScript fails to handle both elements:

In this case html variable bears only the first div content ("a") .

What's the difference between an id and a class?

What’s the difference between <div > and <div > when it comes to CSS? Is it alright to use <div > ?

I see different developers doing this in both ways, and since I’m self taught, I’ve never really figured it out.

Cleptus's user avatar

17 Answers 17

ids must be unique where as class can be applied to many things. In CSS, id s look like #elementID and class elements look like .someClass

In general, use id whenever you want to refer to a specific element and class when you have a number of things that are all alike. For instance, common id elements are things like header , footer , sidebar . Common class elements are things like highlight or external-link .

It’s a good idea to read up on the cascade and understand the precedence assigned to various selectors: http://www.w3.org/TR/CSS2/cascade.html

The most basic precedence you should understand, however, is that id selectors take precedence over class selectors. If you had this:

The text would be red because the id selector takes precedence over the class selector.

Perhaps an analogy will help understanding the difference:

Student ID cards are distinct. No two students on campus will have the same student ID card. However, many students can and will share at least one Class with each other.

It’s okay to put multiple students under one Class title, such as Biology. But it’s never acceptable to put multiple students under one student ID.

When giving Rules over the school intercom system, you can give Rules to a Class:

«Tomorrow, all students are to wear a red shirt to Biology class.»

Or you can give rules to a Specific Student, by calling his unique ID:

«Jonathan Sampson is to wear a green shirt tomorrow.»

In this case, Jonathan Sampson is receiving two commands: one as a student in the Biology class, and another as a direct requirement. Because Jonathan was told directly, via the id attribute, to wear a green shirt, he will disregard the earlier request to wear a red shirt.

The more specific selectors win.

Sampson's user avatar

Where to use an ID versus a class

The simple difference between the two is that while a class can be used repeatedly on a page, an ID must only be used once per page. Therefore, it is appropriate to use an ID on the div element that is marking up the main content on the page, as there will only be one main content section. In contrast, you must use a class to set up alternating row colors on a table, as they are by definition going to be used more than once.

IDs are an incredibly powerful tool. An element with an ID can be the target of a piece of JavaScript that manipulates the element or its contents in some way. The ID attribute can be used as the target of an internal link, replacing anchor tags with name attributes. Finally, if you make your IDs clear and logical, they can serve as a sort of “self documentation” within the document. For example, you do not necessarily need to add a comment before a block stating that a block of code will contain the main content if the opening tag of the block has an ID of, say, «main», «header», «footer», etc.

Type, class, and ID selectors

In this lesson, we examine some of the simplest selectors, which you will probably use most frequently in your work.

Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)
Objective: To learn about the different CSS selectors we can use to apply CSS to a document.

Type selectors

A type selector is sometimes referred to as a tag name selector or element selector because it selects an HTML tag/element in your document. In the example below, we have used the span , em and strong selectors.

Try adding a CSS rule to select the <h1> element and change its color to blue.

The universal selector

The universal selector is indicated by an asterisk ( * ). It selects everything in the document (or inside the parent element if it is being chained together with another element and a descendant combinator). In the following example, we use the universal selector to remove the margins on all elements. Instead of the default styling added by the browser — which spaces out headings and paragraphs with margins — everything is close together.

This kind of behavior can sometimes be seen in «reset stylesheets», which strip out all of the browser styling. Since the universal selector makes global changes, we use it for very specific situations, such as the one described below.

Using the universal selector to make your selectors easier to read

One use of the universal selector is to make selectors easier to read and more obvious in terms of what they are doing. For example, if we wanted to select any descendant elements of an <article> element that are the first child of their parent, including direct children, and make them bold, we could use the :first-child pseudo-class. We will learn more about this in the lesson on pseudo-classes and pseudo-elements, as a descendant selector along with the <article> element selector:

However, this selector could be confused with article:first-child , which will select any <article> element that is the first child of another element.

To avoid this confusion, we can add the universal selector to the :first-child pseudo-class, so it is more obvious what the selector is doing. It is selecting any element which is the first-child of an <article> element, or the first-child of any descendant element of <article> :

Although both do the same thing, the readability is significantly improved.

Class selectors

The class selector starts with a dot ( . ) character. It will select everything in the document with that class applied to it. In the live example below we have created a class called highlight , and have applied it to several places in my document. All of the elements that have the class applied are highlighted.

Targeting classes on particular elements

You can create a selector that will target specific elements with the class applied. In this next example, we will highlight a <span> with a class of highlight differently to an <h1> heading with a class of highlight . We do this by using the type selector for the element we want to target, with the class appended using a dot, with no white space in between.

This approach reduces the scope of a rule. The rule will only apply to that particular element and class combination. You would need to add another selector if you decided the rule should apply to other elements too.

Target an element if it has more than one class applied

You can apply multiple classes to an element and target them individually, or only select the element when all of the classes in the selector are present. This can be helpful when building up components that can be combined in different ways on your site.

In the example below, we have a <div> that contains a note. The grey border is applied when the box has a class of notebox . If it also has a class of warning or danger , we change the border-color .

We can tell the browser that we only want to match the element if it has two classes applied by chaining them together with no white space between them. You’ll see that the last <div> doesn’t get any styling applied, as it only has the danger class; it needs notebox as well to get anything applied.

ID selectors

An ID selector begins with a # rather than a dot character, but is used in the same way as a class selector. However, an ID can be used only once per page, and elements can only have a single id value applied to them. It can select an element that has the id set on it, and you can precede the ID with a type selector to only target the element if both the element and ID match. You can see both of these uses in the following example:

Warning: Using the same ID multiple times in a document may appear to work for styling purposes, but don’t do this. It results in invalid code, and will cause strange behavior in many places.

Note: As we learned in the lesson on specificity, an ID has high specificity. It will overrule most other selectors. In most cases, it is preferable to add a class to an element instead of an ID. However, if using the ID is the only way to target the element — perhaps because you do not have access to the markup and cannot edit it — this will work.

Summary

That wraps up Type, class, and ID selectors. We’ll continue exploring selectors by looking at attribute selectors.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом