Какие вы знаете способы организации css кода

Заключение. Рекомендации по CSS

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

Комментирование кода

Когда вам (или другому разработчику) приходится обращаться к CSS-таблице через продолжительное время (месяц, полгода, год и т. п.), то при взгляде на код может возникнуть вопрос: «К чему он относится? Каково его действие?». Чтобы таких вопросов не возникало либо возникало меньше, необходимо добавлять комментарии к коду. Конечно, не нужно комментировать, что делает каждое свойство. Однако описательный комментарий будет уместным, например, возле кода CSS-анимации, при взгляде на который можно не сразу понять, что он делает.

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

Понятные имена для селекторов

У профессионала должен быть развит такой навык как умение давать хорошие имена селекторам. Как правильно придумывать названия? Первый совет: не называйте селектор, исходя из цвета или местоположения элемента. Это те вещи, которые с высокой долей вероятности могут быть изменены в ходе доработки дизайна. Клиент может прислать правки, где попросит сделать кнопку не зеленой, а голубой, и если вы уже назвали класс .green-button , возникнут проблемы: придется либо везде менять .green-button на .blue-button , либо оставить всё как есть, но потом это будет вводить вас (или другого разработчика) в заблуждение. То же самое касается привязки к местоположению: элемент .left-block вскоре может стать элементом .right-block , потому что дизайнер или заказчик так захотел. И вновь вы столкнетесь с проблемой несоответствия имени.

Так как же называть селекторы? Более правильным будет давать такие имена, которые указывают на назначение элемента либо действие стиля. Например, кнопка отмены может называться .cancel-button , форма для обратного звонка — .callback-form , всплывающее окно — .popup-window и так далее. Если вы создаете класс для выравнивания текста по центру, то будет уместным назвать его как-то вроде .text-center :

Также не стоит давать селекторам бессмысленные имена вроде #b1 , .sb , .abc и т. п., поскольку потом ни вы, ни другие разработчики не сможете понять, что же означают эти загадочные названия.

Несколько классов для одного элемента

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

Однако первая кнопка должна быть выровнена по левому краю, вторая — по центру, а третья — по правому краю. Как это сделать? Самое очевидное решение — создать дополнительные классы специально для выравнивания блочного элемента:

По сути, класс .block-left можно и не создавать, поскольку наша кнопка по умолчанию примыкает к левому краю. Итак, нужный класс теперь можно использовать в паре с классом .button :

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

Группирование стилей

Если ваша таблица стилей содержит всего десяток правил, то проблем с ее восприятием не возникнет. Но в реальной жизни даже совсем небольшой проект может иметь более 500 строк CSS-кода. И если вы будете записывать все правила подряд, без разбивки на группы, вы очень скоро запутаетесь в своей же работе. Отыскать нужное правило будет сложно, поддержка такой CSS-таблицы превратится в мучение.

Если вы проходили практические уроки данного учебника, то помните, что мы делили таблицу стилей на разделы при помощи комментариев и говорили вам записывать стили в соответствующую группу.

Железных правил относительно организации групп в CSS-файле не существует. Однако есть несколько популярных приемов, которые помогут удобно сгруппировать стили:

Группируйте стили, которые относятся к определенной секции страницы. Например, стили для шапки сайта помещайте в одну группу, стили для футера — в другую, стили для навигации — в третью и т. д.

Группируйте стили, относящиеся к одной задаче. К примеру, стили для разметки размещайте в одной группе, стили для форматирования — в другой и т. д.

Для выделения групп используйте обычные CSS-комментарии. Это общепринятый способ создания разделов в таблицах стилей. Комментарии старайтесь оформлять так, чтобы они были хорошо заметны. Например:

Вы можете придумать другой удобный для себя вариант оформления комментариев, главное, следите за тем, чтобы комментарий начинался с символов /* и заканчивался символами */ , и между ними не было такой же комбинации символов (во избежание ошибок).

Несколько CSS-таблиц

Когда таблица стилей расширяется до огромных размеров, становится неудобно искать и редактировать в ней стили. В этом случае удобным решением может стать разделение одной CSS-таблицы на несколько файлов. Безусловно, здесь нужно иметь чувство меры: не стоит создавать 20-40 штук файлов со стилями для каждой секции сайта (это сильно загрузит веб-сервер), однако будет разумным разъединить большие группы стилей. Например, вы можете поместить код разметки в файл layout.css , основные стили — в main.css , медиа-запросы — в media.css и т. д.

Затем понадобится подключить все эти файлы к HTML. Можно добавить каждый файл по отдельности через тег
, но есть способ получше: создайте отдельную внешнюю таблицу стилей (скажем, styles.css ), внутри которой используйте правило @import для подключения всех остальных таблиц стилей:

В принципе, это весь код, который должна содержать таблица styles.css . Подключите ее к HTML-документу (другие таблицы подключать этим образом не нужно):

Читайте также:  Способы зажжения олимпийского огня

Теперь, когда веб-страница будет загружаться, браузер загрузит файл styles.css , который, в свою очередь, скажет браузеру загрузить три остальные таблицы стилей.

Препроцессоры CSS

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

Среди преимуществ препроцессоров стоит выделить:

Переменные CSS. С помощью препроцессора вы можете определять CSS-переменные, которые хранят нужные значения. Например, если вам необходимо использовать определенный цвет для многих элементов сайта, вы указываете этот цвет в формате HEX каждый раз для каждого элемента. Если потом понадобится изменить этот цвет на другой, вам придется проходиться по всем стилям, где он используется. Переменная CSS позволяет указать этот цвет один раз, в начале таблицы стилей. Если затем вам придется менять этот цвет, вы просто поменяете значение в переменной.

Добавление префиксов. В нашем учебнике мы не раз упоминали о необходимости дописывать префиксы производителей к некоторым свойствам. Препроцессор CSS избавит вас от необходимости делать это и добавит все необходимые вендорные префиксы сам.

Объединение CSS-файлов. При разработке удобно хранить CSS-стили разного назначения в отдельных файлах. Но при загрузке нескольких таблиц стилей увеличивается количество обращений к веб-серверу. И когда идет борьба за каждую миллисекунду в скорости загрузки сайта, может понадобиться объединить все CSS-таблицы в один большой файл. Препроцессор позволяет держать ваш код CSS в разных файлах для удобства разработки, а в качестве финального файла, который будет размещен на сервере, объединить все стили в одну внешнюю таблицу. Он также уберет из конечного файла все лишнее, включая комментарии.

Самые распространенные препроцессоры

, а на другой — тег

Существуют и другие модели организации кода: BEM, SMACSS, Atomic CSS и т. д. У каждого из этих подходов есть свои преимущества и недостатки. Какой из них выбрать — решать вам как разработчику, опираясь на собственный опыт и предпочтения. Кроме того, ничто не мешает вам выработать свой способ организации CSS. Быть может, именно придуманный вами вариант позволит веб-разработке подняться на новый уровень!

Завершение

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

Источник

Организация CSS-кода

As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability.

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 some tips and best practices for organizing stylesheets, and find out about some of the naming conventions and tools in common usage to help with CSS organization and team working.

Tips to keep your CSS tidy

Here are some general suggestions for ways to keep your stylesheets organised and tidy.

Does your project have a coding style guide?

If you are working with a team on an existing project, the first thing to check is whether the project has an existing style guide for CSS. The team style guide should always win over your own personal preferences. There often isn’t a right or wrong way to do things, but consistency is important.

Keep it consistent

If you get to set the rules for the project or are working alone, then the most important thing to do is to keep things consistent. Consistency can be applied in all sorts of ways, such as using the same naming conventions for classes, choosing one method of describing color, or maintaining consistent formatting (for example will you use tabs or spaces to indent your code? If spaces, how many spaces?)

Having a set of rules you always follow reduces the amount of mental overhead needed when writing CSS, as some of the decisions are already made.

Formatting readable CSS

There are a couple of ways you will see CSS formatted. Some developers put all of the rules onto a single line, like so:

Other developers prefer to break everything onto a new line:

CSS doesn’t mind which one you use. We personally find it is more readable to have each property and value pair on a new line.

Comment your CSS

Adding comments to your CSS will help any future developer work with your CSS file, but will also help you when you come back to the project after a break.

A good tip is to add a block of comments between logical sections in your stylesheet too, to help locate different sections quickly when scanning through, or even give you something to search for to jump right into that part of the CSS. If you use a string which won’t appear in the code you can jump from section to section by searching for it — below we have used || .

You don’t need to comment every single thing in your CSS, as much of it will be self-explanatory. What you should comment are the things where you made a particular decision for a reason.

You may have used a CSS property in a specific way to get around older browser incompatibilities, for example:

Perhaps you followed a tutorial to achieve something, and the CSS is a little non-obvious. In that case you could add the URL of the tutorial to the comments. You will thank yourself when you come back to this project in a year or so, and can vaguely remember there was a great tutorial about that thing, but where is it?

Читайте также:  Способы оформления слоеного теста

Create logical sections in your stylesheet

It is a good idea to have all of the common styling first in the stylesheet. This means all of the styles which will generally apply unless you do something special with that element. You will typically have rules set up for:

  • body
  • p
  • h1 , h2 , h3 , h4 , h5
  • ul and ol
  • The table properties
  • Links

In this section of the stylesheet we are providing default styling for the type on the site, setting up a default style for data tables and lists and so on.

After this section we could define a few utility classes, for example a class that removes the default list style for lists we’re going to display as flex items or in some other way. If you have a few things you know you will want to apply to lots of different elements, they can come in this section.

Then we can add everything that is used sitewide. That might be things like the basic page layout, the header, navigation styling, and so on.

Finally we will include CSS for specific things, broken down by the context, page or even component in which they are used.

By ordering things in this way, we at least have an idea in which part of the stylesheet we will be looking for something that we want to change.

Avoid overly-specific selectors

If you create very specific selectors you will often find that you need to duplicate chunks of your CSS to apply the same rules to another element. For example, you might have something like the below selector, which applies the rule to a

with a class of box inside an with a class of main .

If you then wanted to apply the same rules to something outside of main , or to something other than a

, you would have to add another selector to these rules or create a whole new ruleset. Instead, you could create a class called box and apply that anywhere.

There will be times when making something more specific makes sense, however this will generally be an exception rather than usual practice.

Break large stylesheets into multiple smaller ones

In particular in cases where you have very different styles for distinct parts of the site, you might want to have a stylesheet that includes all the global rules and then smaller ones that include the specific rules needed for those sections. You can link to multiple stylesheets from one page, and the normal rules of the cascade apply, with rules in stylesheets linked later coming after rules in stylesheets linked earlier.

For example, we might have an online store as part of the site, with a lot of CSS used only for styling the product listings and forms needed for the store. It would make sense to have those things in a different stylesheet, only linked to on store pages.

This can make it easier to keep your CSS organised, and also means that if multiple people are working on the CSS you will have fewer situations where two people need to work on the same stylesheet at once, leading to conflicts in source control.

Other tools that can help

CSS itself doesn’t have much in the way of in-built organisation, therefore you need to do the work to create consistency and rules around how you write CSS. The web community has also developed various tools and approaches that can help you to manage larger CSS projects. As they may be helpful for you to investigate, and you are likely to come across these things when working with other people, we’ve included a short guide to some of these.

CSS methodologies

Instead of needing to come up with your own rules for writing CSS, you may benefit from adopting one of the approaches already designed by the community and tested across many projects. These methodologies are essentially CSS coding guides that take a very structured approach to writing and organising CSS. Typically they tend to result in more verbose use of CSS than you might have if you wrote and optimised every selector to a custom set of rules for that project.

However, you do gain a lot of structure by adopting one and, as many of these systems are very widely used, other developers are more likely to understand the approach you are using and be able to write their CSS in the same way, rather than having to work out your own personal methodology from scratch.

OOCSS

Most of the approaches that you will encounter owe something to the concept of Object Oriented CSS (OOCSS), an approach made popular by the work of Nicole Sullivan. The basic idea of OOCSS is to separate your CSS into reusable objects, which can be used anywhere you need on your site. The standard example of OOCSS is the pattern described as The Media Object. This is a pattern with a fixed size image, video or other element on one side, and flexible content on the other. It’s a pattern we see all over websites for comments, listings, and so on.

If you are not taking an OOCSS approach you might create custom CSS for the different places this pattern is used, for example creating a class called comment with a bunch of rules for the component parts, then a class called list-item with almost the same rules as the comment class except for some tiny differences. The differences between these two components is that the list-item has a bottom border, and images in comments have a border whereas list-item images do not.

In OOCSS, you would create one pattern called media that would have all of the common CSS for both patterns — a base class for things that are generally the shape of the media object. Then we’d add an additional class to deal with those tiny differences, thus extending that styling in specific ways.

Читайте также:  Решим систему матричным способом для этого вычислим обратную матрицу

In your HTML the comment would need both the media and comment classes applied:

The list-item would have media and list-item applied:

The work that Nicole Sullivan did in describing this approach and promoting it means that even people who are not strictly following an OOCSS approach today will generally be reusing CSS in this way — it has entered our understanding as a good way to approach things in general.

BEM stands for Block Element Modifier. In BEM a block is a standalone entity such as a button, menu, or logo. An element is something like a list item or a title that is tied to the block it is in. A modifier is a flag on a block or element that changes the styling or behavior. You will be able to recognise code that uses BEM due to the extensive use of dashes and underscores in the CSS classes. For example, look at the classes applied to this HTML from the page about BEM Naming conventions:

The additional classes are similar to those used in the OOCSS example, however they use the strict naming conventions of BEM.

BEM is widely used in larger web projects and many people write their CSS in this way. It is likely that you will come across examples, even in tutorials, that use BEM syntax, without mentioning why the CSS is structured in such a way.

To read more about the system read BEM 101 on CSS Tricks.

Other common systems

There are a large number of these systems in use. Other popular approaches include Scalable and Modular Architecture for CSS (SMACSS), created by Jonathan Snook, ITCSS from Harry Roberts, and Atomic CSS (ACSS), originally created by Yahoo!. If you come across a project that uses one of these approaches then the advantage is that you will be able to search and find many articles and guides to help you understand how to code in the same style.

The disadvantage of using such a system is that they can seem overly complex, especially for smaller projects.

Build systems for CSS

Another way to organise CSS is to take advantage of some of the tooling that is available for front-end developers, which allows you to take a slightly more programmatic approach to writing CSS. There are a number of tools which we refer to as pre-processors and post-processors. A pre-processor runs over your raw files and turns them into a stylesheet, whereas a post-processor takes your finished stylesheet and does something to it — perhaps to optimize it in order that it will load faster.

Using any of these tools will require that your development environment can run the scripts that do the pre and post-processing. Many code editors can do this for you, or you can install command line tools to help.

The most popular pre-processor is Sass. This is not a Sass tutorial, so I will briefly explain a couple of the things that Sass can do, which are really helpful in terms of organisation, even if you don’t use any of the other Sass features.

Defining variables

CSS now has native custom properties, making this feature increasingly less important, however one of the reasons you might use Sass is to be able to define all of the colors and fonts used in a project as settings, then use that variable around the project. This means that if you realise you have used the wrong shade of blue, you only need change it in one place.

If we created a variable called $base-color as in the first line below, we could then use it through the stylesheet anywhere that required that color.

Once compiled to CSS, you would end up with the following CSS in the final stylesheet.

Compiling component stylesheets

I mentioned above that one way to organise CSS is to break down stylesheets into smaller stylesheets. When using Sass you can take this to another level and have lots of very small stylesheets — even going as far as having a separate stylesheet for each component. By using the include functionality in Sass these can then all be compiled together into one, or a small number of stylesheets to actually link into your website.

You can see how one developer approaches the problem in this blog post.

Note: A simple way to try out Sass is to use CodePen — you can enable Sass for your CSS in the Settings for a Pen, and CodePen will then run the Sass parser for you, in order that you can see the resulting webpage with regular CSS applied. Sometimes you will find that CSS tutorials have used Sass rather than plain CSS in their CodePen demos, so it is handy to know a little bit about it.

Post-processing for optimization

If you are concerned about adding size to your stylesheets by adding a lot of additional comments and whitespace for example, then a post-processing step could be to optimize the CSS by stripping out anything unneccessary in the production version. An example of a post-processor solution for doing this would be cssnano.

Wrapping up

This is the final part of our Learning CSS Guide, and as you can see there are many ways in which your exploration of CSS can continue from this point.

To learn more about layout in CSS, see the Learn CSS Layout section.

You should also now have the skills to explore the rest of the MDN CSS material. You can look up properties and values, explore our CSS Cookbook for patterns to use, and read more in some of the specific guides such as our Guide to CSS Grid Layout.

Источник

Оцените статью
Разные способы