Css use classes or ids

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 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 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 element selector:

article :first-child  font-weight: bold; > 

However, this selector could be confused with article:first-child , which will select any 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 element, or the first-child of any descendant element of :

article *:first-child  font-weight: bold; > 

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 with a class of highlight differently to an 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 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 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.

Found a content problem with this page?

This page was last modified on Jun 30, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

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

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

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

Селектор ID используется для обозначения отдельного HTML-элемента с помощью уникального значения атрибута id . В следующем примере представлен элемент , значением атрибута 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 , а также понять, как правильно использовать:

 
Ссылка 1 Ссылка 2 Ссылка 3 Ссылка 4

Это наш первый абзац.

Это наш второй абзац.

Это наш третий абзац.

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

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

#container < width: 1080px; margin: 0 auto; background: #eee >#menu < height: 90px; background: #ddd >.link < color: #000; text-decoration: none >#content < padding: 20px >.text

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

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

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

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

Этот пункт не имеет границ.

Этот пункт имеет границы.

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

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

Источник

Why use Classes or IDs on the HTML element?

…and skip the class name. After all, there is guaranteed to only be one element, right? I see Nicolas’ point. If you view source and look at a page in isolation, I can see how any class or ID on the element seems superfluous. The fact is, these top-level classes can be extremely useful. Let’s review the theory and see some real word examples.

The idea of CSS is to abstract design away from markup. One hundred pages on a site may all use the same exact CSS file. This is efficient for many reasons, one of which is that changes to design happen in one place, rather than one hundred. A top-level class can serve to identify which page is currently being viewed and thus apply styling to that a different page may not get. Different pages, same CSS file, different designs. And because this is happening at the highest level possible element, you can control the entire pages design through a single class hook.

A WordPress powered site uses themes to display pages. All pages on the site are built from the active theme. This theme has a file in it called header.php which outputs the top of all the pages, like the doctype, head, and opening body and html tags. WordPress has a function called body_class() which outputs a whole bunch of classes that are specific to the type of page being loaded. Most themes have an opening body tag like this:

Now there are a bunch of hooks you can use in the CSS file to style things uniquely based on the kind of page. For example:

I’m not entirely sure why WordPress calls it “body_class”, as you can (and it’s often useful to) style the HTML element directly. Just as an FYI, you can absolutely just move the function up to the HTML element.

Modernizr is a JavaScript library that also adds top level classes. It adds them dynamically to the html element when it loads and runs. The classes are symbolic of what the current browsers capabilities are. So whereas WordPress applies classes you can use to make different pages look different, Modernizer applies classes you can use to make the same page look different, depending on browser capabilities. This is what an html element might look like after Modernizr:

section < background: url(boring-fallback.jpg); >.multiplebgs section

I have an older article which covers this same idea and the classic tip of using this idea to do current navigation highlighting. Check it out for some other tips. Please share if you have some other use-cases for using top-level classes.

Источник

Читайте также:  Php artisan make policy
Оцените статью