Atomic css что это

Atomic CSS

Плюсы перед семантической моделью (классической).

1. Независимость от имен. (Универсальность имен).

2. Универсальность классов.

3. Читабельность классов (При правильной организации, конечно же).

FAQ (Ответы):

1. Чем это не inline верстка в атрибуте style?

2. Чем это удобно, если очень много нужно писать классов в элемент?

3. А если у вас много одинаковых элементов ваш atomic сss сдуется, пфф?

А если их очень много и если вдруг нужно их все сразу изменить?

4. Что будет если макет предназначен только для обертки мощной Backend части, не будет ли избыток классов в html или другой разметке мешать Backend программистам?

5. Кто использует эту модель?(human proves)

Как выглядит атомарный класс.

Варианты: width100px, width-100px, w100px, w-100px, wh100px, wh-100px и т.д.
Можно писать, как вам удобно, но чтоб это передавало свойство. События делаются обычными псевдоклассами: hover, focus, active.

Инструменты для работы с Atomic CSS.

Orna и Atomizer

Atomizer – node.js модуль для создания Atomic CSS от Yahoo.

Как он работает? Вы пишете html разметку и в элементах пишете атомарные классы по структуре атомайзера. Атомайзер считывает документ и создает atomic.css файл с классами названия которых были прописаны в атрибутах class.

Пример:

class=»Bgc(#0280ae.5) C(#fff) P(20px)»

    При таком подходе:

Рекомендация: Atomizer хорош для больших сайтов, все компилируется в отдельный файл css, но сначала немного сложен.

Orna (OrnaJS) – javascript парсер на основе jquery, который работает в браузере на стороне клиента и подключается непосредственно в документ. В отличии от Атомайзера, который не подключается в документ, а подключается ранее сгенерированный им css файл. Классы Орна пишутся по определенной структуре, которая почти и местами вообще не отличается от css. Орна задает классы напрямую элементам без файла css. Вот и нюанс c js, классы задание ним не кэшируються и переопределяются с перезагрузкой страницы. Но это хорошо для динамики. По сути Орна это генератор атомарных классов. Супер для работы с ReactJS и Handlebars.JS. Есть также версия Орны для Node.js (Orna4Node), которая генерирует классы в CSS файл, как Atomizer.

Пример:

class=»background-color_red background-color_black_click color_white height_100px»

class=»bgc_red bgc_black_click c_white h_100px»

Орна поймет оба примера!

    При таком подходе:

Рекомендация: Орна парсит документ каждый раз при перезагрузке страницы, файлы не кэшируются, потому она лучше для небольших сайтов или как дополнение.

. Orna и Atomizer умеют работать с событиями мыши и дочерними элементами через родительский.

Общая рекомендация: разберитесь в Atomic CSS, не устраивайте холивары и пишите свое адекватное мнение в комментарии.
Хороший комплект для работы и динамического рендера(отрисовки) страницы: OrnaJS + ReactJS. Предварительное создание CSS: Orna4Node или Atomizer.

Источник

Атомный CSS как набор инструментов

Растущая сложность веб-сайтов и веб-приложений привела к появлению нескольких новых подходов к структурированию и поддержке таблиц стилей. Возможно, вы слышали о BEM, OOCSS, SMACSS, OrganicCSS или Atomic CSS. Мы использовали последний, Atomic CSS, для разработки нашего нового веб-сайта golucid.co. Мы хотели бы поделиться с вами, где это помогло, где это больно, и как мы нашли баланс.

Что такое атомарный CSS?

Давайте начнем с простого определения. Как следует из названия, основной принцип Atomic CSS заключается в разделении стилей на атомарные или неделимые части. Это в корне противоречит традиционному подходу написания семантических селекторов. Сравните два фрагмента CSS ниже:

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

Как это работает

Смена парадигмы в атомарном CSS заключается в том, что большинство решений по стилю находятся в разметке, а не явно в таблице стилей. (Постарайтесь не обращать внимания на этот голос в вашей голове, кричащий о разделении интересов — мы скоро доберемся до хорошего!) из golucid.co :

Сокращение избыточности кода и размера

Атомный CSS — все о борьбе с раздутием, которое имеют тенденцию приобретать наши таблицы стилей. Рассмотрим следующий фрагмент семантического CSS:

Вы заметите, что есть несколько экземпляров свойства margin с одинаковым значением. Запахнув дублирующийся код, опытный автор препроцессора может заменить значение переменной следующим образом:

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

Давайте воспроизведем наш стиль с использованием атомарного подхода:

Атомность частей способствует минимальному раздутию CSS и оптимальному повторному использованию кода. Действительно, HTML более раздутый из-за увеличения числа используемых имен классов, но дизайнеры из Yahoo сообщили о чистой экономии общего размера между CSS и HTML.

Почему бы просто не использовать встроенные стили?

В этот момент вы можете спросить себя: чем это отличается / лучше / хуже, чем просто использование встроенных стилей в моем HTML?

Во-первых, встроенные стили являются королем в области специфики. Атомарные CSS-классы — это просто простые классы с низкой специфичностью, что означает, что вы можете легко и удобно переопределять атомарные CSS-стили без неприятной цепочки специфичности.

Во-вторых, встроенные стили неприглядны, раздувают ваш HTML как сумасшедший и его сложно поддерживать. Атомные таблицы стилей являются чистыми, лаконичными и легко обслуживаемыми.

Почему вы должны попробовать это

Теперь о твердой продаже — вы должны действительно попробовать это. Мы не говорим, что это идеальное решение всех ваших проблем CSS, но это, безусловно, инструмент, который стоит изучить. Вот почему нам это нравится до сих пор:

Согласованность стиля

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

Атомные стили облегчают изменения

Допустим, вы хотите изменить стандартное поле с 16 на 20 пикселей или изменить основной цвет с синего на фиолетовый. При использовании встроенных стилей вам придется пройти весь проект, чтобы найти и заменить их все. С атомарной таблицей стилей вы просто вносите изменения в нескольких местах. Вам, вероятно, потребуется изменить его только в одном месте, если вы используете препроцессор CSS и переменные.

Улучшенный рабочий процесс

Атомный CSS позволяет быстро создавать основные вещи. Таким образом, вы можете потратить время на написание пользовательских стилей для более интересных элементов вашего дизайна. Лучшая часть использования атомарных стилей для сборки golucid.co заключалась в том, что нам не нужно было писать новые стили для каждого нового элемента HTML. Несколько раз мы начинали писать новые семантические классы только для того, чтобы понять, что один и тот же стиль можно применять только с нашими атомарными классами. Таблица стилей начиналась с малого и осталась такой же.

Предостережения

Несмотря на то, что мы нашли преимущества в атомарном подходе, мы также столкнулись с некоторыми недостатками, наиболее заметный из которых касался адаптивного дизайна. Например, если ваш основной раздел имеет класс m-3 для поля в 30px, но вы хотите уменьшить его до 15px при небольшой ширине устройства, вам потребуется использовать другой класс, например m-3-sm, в дополнение к твой м-3 класс. В этот момент 3 в м-3-см теряет часть своего значения. Легко видеть, что добавление большого количества адаптивных классов может сделать разметку громоздкой и увеличить таблицу стилей.

Вывод

Атомный CSS — отличный инструмент, когда он настроен в соответствии с вашими потребностями. Например, вы можете использовать семантические классы для визуального оформления (цвета, границы, фоны и т. Д.) И атомарные классы для разметки и разметки. Вы также можете создать немного более сложные классы для вашей атомарной таблицы стилей, которые заменят часто встречающийся набор стилей (некоторые называют эти классы «молекулами»). Важно то, что Atomic CSS отвечает вашим потребностям, а не наоборот.

Источник

Frequently Asked Questions

This section is intended to answer common questions related to Atomic CSS, ACSS, and Atomizer. If you’re unable to find an answer to your question, you can find support here or start a discussion here.

Questions related to the Atomic CSS architecture

Questions related to ACSS and Atomizer

Answers related to the Atomic CSS architecture

What is Atomic CSS?

Atomic CSS is a collection of single purpose styling units (single responsibility principle for maximum reuse) that fits well with components in templated frameworks such as React, Ember, or Angular.

Atomic classes and their associated styling are immutable, meaning you’d use the same classes whatever the project you’re working on or the team you’re working with. In other words, Atomic CSS is a common «vocabulary» meant to style documents regardless of context or content.

For more information about Atomic CSS, we recommend that you read Challenging CSS best practices on Smashing Magazine, watch the Atomic CSS presentation on youtube, or check the Atomic CSS slide deck on haikudeck.

Note that the above materials are relatively «old» and some of their content may have changed.

How is Atomic CSS different than using inline styles?

Atomic css что это. Смотреть фото Atomic css что это. Смотреть картинку Atomic css что это. Картинка про Atomic css что это. Фото Atomic css что это

The difference between inline styling and Atomic CSS

Inline stylingAtomic CSS
Specificity1.0.0.00.0.1.0 [1]
VerbosityHighMinimal
AbstractionNoneFallbacks, tweaks, LTR/RTL support, etc.

What are the benefits of Atomic CSS?

The main benefit of Atomic CSS is that it prevents bloat by dramatically reducing redundancy. This is possible because rules are content agnostic which makes them much more re-usable than rules based on «semantic» selectors (names that relate to what is styled).

This speaks for itself:

For the sake of readability, CSS classes on this page do not include the escape character ( \ ) where it should be needed.

Such approach produces less of everything:

Table comparing yahoo.com against other web sites

rulesselectorsdeclarationspropertiesfont-sizeKB
twitter.com6,372 [2]9,10415,000135755585
facebook.com3,3164,0187,947103157281
medium.com3,0904,0307,321150432282
youtube.com3,5304,6849,005136336352
tumblr.com5,647 [2]7,61618,100253499733
yahoo.com1,8912,3114,57912471189
rulesselectorsdeclarationspropertiesfont-sizeKB

The table above uses yahoo.com for reference as this site used—at the time this was published—a static Atomic CSS library.

Should I «atomize» everything? Should I style everything using atomic classes?

If changing some styling requires you to edit multiple files, then you should use the classic CSS approach: apply a «meaningful» class to the element you want to style and use that hook to write rules in a style sheet. But if changing a given style across the board can be done in one place—other than a style sheet—then you should go with Atomic CSS.

An example of the former could be headings (unless they are «components») meant to look the same across many modules, or any other styling meant to be shared across different modules. An example of the latter is a component that lives in a template or a JS file, like a specific widget with its own styling.

I have always been told to use classes related to content, not to presentation. Isn’t Atomic CSS promoting bad practice?

Despite the HTML5 specification section on classes repeating the assumed “best practice” that…

…authors are encouraged to use [class attribute] values that describe the nature of the content, rather than values that describe the desired presentation of the content.

…there is no inherent reason to do this. In fact, it’s often a hindrance when working on large websites or applications.

The main goal of Atomic CSS is to reduce bloat, so to better achieve this we must ignore content and context as much as possible.

Isn’t Atomic CSS moving bloat from style sheets to HTML?

The table below represents the average number of characters per class attribute on a page. Note that Facebook appears to uglify some classes.

Number of characters per class attributes between web sites

Number of characters per @class
twitter.com28
facebook.com17 [4]
usatoday.com38
theguardian.com36
yahoo.com22

The table above uses yahoo.com for reference as this site uses an early version of Atomic CSS.

Gzip loves Atomic CSS

If we put Gzip into the picture, then things look even better. That’s because a lot of repetitions means a better compression ratio. From a few tests we ran, it’s about 35% for semantic classes versus 48% for atomic classes.

How can you distribute presentation changes without asking everyone to change their markup?

Use atomic classes where it makes sense; for example the following creates much of the content of our reference page. If we decided to change the styling of this content this would be the only place we’d need to go to.

Please visit our RWD docs to see examples of how you can use ACSS to create styles in the context of breakpoints.

Answers related to Atomizer

How does ACSS compare to Bootstrap, PureCSS, or other CSS framework?

ACSS is not a framework; it does not contain UI components nor a grid system. It is a solution that allows you to to create your own UI while preventing bloat.

Do I need to specify a namespace? And if yes, what should I use?

You do not need to use a namespace per se but this is extremely useful to bump the specificity of Atomic rules. Our advice is to use an id (we use #atomic ) so all Atomic rules can easily overwrite declarations from other rules; for example:

We like to deal with 5 «specificity» brackets:

This clear separation helps to better manage styles inside large scale projects.

Why are ACSS classes capitalized? As far as I know, no other framework does that?

We took advantage of the fact that nobody seems to capitalize classes and that CSS is case sensitive to get a «cheap» namespace, one that does not rely on extra character(s).

Why do I have to use lowercase for color values?

To prevent redundancy, we made the choice to favor lowercase over uppercase, even though the latter is valid.

This is because classes such as C(#fff) and C(#FFF) would not duplicate the declaration but would add an unnecessary selector to the style sheet.

The reason for this is because including the namespace in the selector could make the rule fail to target the node. For example this would not work (using atomic as the namespace):

This is because including the namespace would create the following rule:

Keep this in mind in case you need to style that same node with JavaScript.

How can one remember Atomic class names?

The syntax comes from Emmet, which is a plugin for many IDEs. It allows you to type a few characters and get property/value pairs. Like Emmet shortcuts, ACSS classes are for the most part simple abbreviations.

The syntax and reference pages are meant to help you with this; and we may have a plugin for your IDE in the near future.

How come Atomizer is not creating some classes for me?

Make sure your grunt config is set up to scan all the files onto which ACSS classes are applied. See

Источник

CSS for component-based frameworks

CSS is painful

CSS is a critical piece of the frontend toolkit, but it’s hard to manage, especially in large projects. Styles are written in a global scope, which is narrowed through complex selectors. Specificity issues, redundancy, bloat, and maintenance can become a nightmare. And modular, component-based projects only add to the complexity. ACSS enables you to style directly in your components, avoiding the headache of writing and managing stylesheets.

Style with class

Most approaches to styling inside components rely on inline styles, which are limiting. Atomic CSS, like inline styles, offers single-purpose units of style, but applied via classes. This allows for the use of handy things such as media queries, contextual styling and pseudo-classes. The lower specificity of classes also allows for easier overrides. And the short, predictable classnames are highly reusable and compress well.

Meet Atomizer

Colors

Variables

«Variables» are useful for theming but they can also be used to share a common value across style declarations.

In this example, brandColor is responsible for setting the text color, background color and border color, while columnWidth dictates the width of the first box and the left offset of its sibling.

Contextual selectors

In this example, two identical sets of boxes are styled differently depending on the class applied to their parent element.

Источник

Thinking in Atomic

«Atomic CSS» is a CSS architecture. It is not opinionated; it simply defines a set of classes representing single-purpose styling units.

Atomizer implements the ACSS syntax to help you generate Atomic rulesets. It only creates a style sheet with declarations that are relevant to your project. These style declarations are generated from ACSS classes found within your project, or from custom values defined in the Atomizer config file.

Adopting a Atomic CSS methodology addresses common CSS challenges:

Changes are predictable Because of the single responsibility principle (one one style) it is easy to predict what removing or adding a class will do. Scope is limited There is no reliance on descendant/contextual selectors — styling is done inside «specificity layers». CSS is lean There is very little redundancy and no dead weight (all styles are relevant to the project). Components are portable Classes used to style a component are not specific to that component, hence components can live in any other project that uses Atomizer [2] . Beginner-friendly Writing efficient and correct selectors is often one of the hardest parts of CSS for new developers to master. With Atomic CSS, developers don’t create bloat because they don’t write the selectors, instead they mostly re-use existing classes. This can greatly simplify the learning curve for inexperienced developers.

Who’s Atomic CSS for?

Atomic CSS is for developers who see the benefits of styling «outside of style sheets» — who want to write markup and styles in one place while benefiting from a Atomic architecture. It is a switch of priorities. You don’t maintain style sheets but components.

Be pragmatic

ACSS can live side-by-side with traditional style sheets. In cases where ACSS doesn’t seem the most pragmatic, you can always supplement with inline styles or external stylesheets. Use the right tool for the job.

Traditional style sheets may be helpful for styles that ACSS cannot create, styles for elements that aren’t under your application’s control, or repeating elements that are not componentized [1] .

Grids

Specificity

From 0,0,1,0 to «infinity«

By nature, ACSS classes have very low specificity ( 0,0,1,0 ). Atomizer creates a style sheet in which the specificity of every rule can be increased by the use of a namespace. Best practice is to keep specificity as low as possible, but depending on other rules in your project you may want to include a namespace to increase the weight of ACSS classes.

Keep in mind that the weight of rules is not as important as making sure specificity is homogeneous across rules. For example, styles like these:

are easier to maintain than styles like these:

Choosing to include a namespace or not, and to use a class or a id for the namespace, depends on the weight of rules in other style sheets. For atomic classes to be relevant they must have enough weight to overwrite non-atomic styles. The specificity may be the same as non-atomic styles as long as the atomic style sheet is included after other style sheets.

This table suggests the namespace to use depending on the weight of your other rules (Specificity Calculator).

Namespace consideration

SpecificityNamespace
0,0,1,1No need for a namespace
Less or equal to 0,0,1,1Use html (type) for namespace
Less or equal to 0,0,2,0Use a class for namespace
Less or equal to 0,1,1,0Use a id for namespace
More than 0,1,1,0Use whatever it takes [4]

You can set up a namespace in grunt-atomizer or via the Atomizer command line.

Style sheets organization

Take advantage of the cascade by creating «specificity layers» [3] and loading files in proper order.

Namespace consideration

LayerSpecificityStyle sheets
type selectors0,0,0,xnormalize.css,
base.css,
etc.
single class0,0,1,0helpers.css,
utility.css,
etc.
contextual selectors
(any number of classes)
0,0,x,xlayout.css,
custom.css,
etc.
ACSS classes0,1,1,0atomic.css
@style1,0,0,0Inline Styles
!important ruleTrumps all the above [5] Can be anywhere
(as an exception)

This web site uses flat selectors ( 0,0,1,0 ) which allows us to follow the same logic as above without the need for a namespace.

Источник

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

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