Мультиклассы

Мультиклассы

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

Синтаксис

Здесь E — обозначает любой тег.

В стилях допустимо использовать запись следующего вида.

В таком случае стиль применяется только для элементов, у которых одновременно заданы классы class1 и class2 , т. е. в коде HTML используется конструкция .

HTML5 CSS 2.1 IE Cr Op Sa Fx

        
Paint.NET Photoshop цвет фон палитра слои свет панели линия прямоугольник пиксел градиент

Результат данного примера показан на рис. 1.

Цвет и размер ссылок, заданный через классы

Рис. 1. Цвет и размер ссылок, заданный через классы

Браузеры

Браузер IE до версии 7.0 некорректно работает с мультиклассами и понимает запись .a.b как .b , т.е. воспринимает только имя последнего класса, что приводит к ошибкам.

CSS по теме

Источник

Мультиклассы

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

Синтаксис

Здесь E — обозначает любой тег.

В стилях допустимо использовать запись следующего вида.

В таком случае стиль применяется только для элементов, у которых одновременно заданы классы class1 и class2 , т. е. в коде HTML используется конструкция .

HTML5 CSS 2.1 IE Cr Op Sa Fx

        
Paint.NET Photoshop цвет фон палитра слои свет панели линия прямоугольник пиксел градиент

Результат данного примера показан на рис. 1.

Цвет и размер ссылок, заданный через классы

Рис. 1. Цвет и размер ссылок, заданный через классы

Браузеры

Браузер IE до версии 7.0 некорректно работает с мультиклассами и понимает запись .a.b как .b , т.е. воспринимает только имя последнего класса, что приводит к ошибкам.

CSS по теме

Источник

Multiple Class / ID and Class Selectors

They look nearly identical, but the top one has no space between #header and .callout while the bottom one does. This small difference makes a huge difference in what it does. To some of you, that top selector may seem like a mistake, but it’s actually a quite useful selector. Let’s see the difference, what that top selector means, and exploring more of that style selector. Here is the “plain English” of #header .callout :

Select all elements with the class name callout that are decendents of the element with an ID of header.

Side-by side comparison of two selectors with the divs they target highlighted. On the left, is an example of a selector that will affect elements with an ID of header and a class of callout. On the right, is an an example that will affect elements with a class of callout that are children of elements with an ID of header.

Maybe this graphic will make that more clear:

Combinations of Classes and IDs

The big point here is that you can target elements that have combinations of class es and ID s by stringing those selectors together without spaces.

Target an element that has all of multiple class es. Shown below with two class es, but not limited to two.

We aren’t limited to only two here, we can combine as many class es and ID s into a single selector as we want.

Although bear in mind that’s getting a little ridiculous. Learn more about how to select IDs, classes, and multiple classes at DigitalOcean.

So how useful is all this really? Especially with ID s, they are supposed to be unique anyway, so why would you need to combine it with a class ? I admit the use cases for the ID versions are slimmer, but there are certainly uses. One of those is overriding styles easily.

Or perhaps prefacing the selector with something even more specific. More useful is multiple class es and using them in the “object oriented” CSS style that is all the rage lately. Let’s say you had a bunch of div s on a page, and you used multiple various descriptive class names on them:

They all share the class “box”, which perhaps sets a width or a background texture, something that all of them have in common. Then some of them have color names as class es, this would be for controlling the colors used inside the box. Perhaps green means the box has a greenish background and light green text. A few of them have a class name of “border”, presumably these would have a border on them while the rest would not. So let’s set something up:

.box < width: 100px; float: left; margin: 0 10px 10px 0; >.red < color: red; background: pink; >.blue < color: blue; background: light-blue; >.green < color: green; background: light-green; >.border

Cool, we have a good toolbox going here, where we can create new boxes and we have a variety of options, we can pick a color and if it has a border or not just by applying some fairly semantic class es. Having this class name “toolbox” also allows us to target unique combinations of these class es. For example, maybe that black border isn’t working on the red boxes, let’s fix that:

Three different colored boxes. A red box, a blue box, and a green box. This image depicts how the multiple class selectors can be used in a way that helps the developer understand what the code is doing.

Based on this demo page.

Also important to note here is that the specificity values of selectors like this will carry the same weight as if they were separate. This is what gives these the overriding power like the example above. Learn more about specificity in CSS at DigitalOcean.

All good current browsers support this as well as IE back to version 7. IE 6 is rather weird. It selects based on the last selector in the list. So “ .red.border ” will select based on just “ .border “, which kinda ruins things. But if you are supporting IE 6, you are used to this kind of tomfoolery anyway and can just fix it with conditional styles.

Источник

How to add multiple classes to HTML elements

Last Updated Jun 18, 2022

Any HTML element can have as many different classes as needed to style the element using CSS effectively.

To assign multiple classes to a single HTML element, you need to specify each class name inside the class attribute separated with a blank space.

For example, the following

element is assigned one class called heading :

 The following example below shows how to assign two classes: heading and font-large to the same paragraph:
 A class name that has more than one word is commonly joined with a dash ( - ) this is also known as the kebab-case.

There is no limit to how many class names you can add to a single HTML element. But keep in mind that you need to keep the class names intuitive and descriptive.

I’d recommend you put 10 class names at maximum in a single HTML element to keep your project maintainable.

HTML multiple classes for styling purpose

HTML classes are used for styling the elements rendered on the browser.

By creating multiple classes that serve different styling purposes, you can reuse the classes in many different elements without having to repeat the styling.

For example, you can have a class called font-small to adjust the font-size property to smaller than regular font size, while the font-large class will make the font-size larger than regular.

Suppose you have a style sheet with the following CSS rules:

You can add the CSS classes above to your HTML elements.

Here’s an example of adding the classes to a element:

  • What property will this class modify? Use it as the first part of your class name.
  • What is the value of the property being modified by this class? Use it as the second part of your class name

For example, if you’re changing the background-color property to grey , then the class name .bg-color-grey would be a good choice.

If the value of the property is not exact, then you can use a word that would describe the output relative to a regular element.

For example, font-small describes that the font size for the assigned element will be smaller than a regular element, so you can use that instead of font-size-12 although the latter is more precise.

Sometimes you can also abbreviate small as sm and create an xs style for extra-small :

Writing good HTML class names takes practice and time because classes can be used by both CSS and JavaScript to manipulate the presentation and the interactivity of HTML pages.

You’re going to get better as you write more code, and the rule of two above will help you start on the right mindset 👍

Now you’ve learned how to assign multiple classes to a single HTML element. Nice work!

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Читайте также:  Java что такое factory
Оцените статью