Do not use empty rulesets что это

Visual Studio Code CSS error «Do not use empty rulesets» [closed]

Want to improve this question? Add details and clarify the problem by editing this post.

I have been using Visual Studio Code for HTML and CSS. I get an error that does not impair the website, but I would like to know more about it. When I hover over the styling for an ID in HTML, a box pops up and says. «Do not use empty rulesets».

Can anyone provide more information on «empty rulesets» and explain why Visual Studio Code (or any other editor) would warn about an empty ruleset?

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

1 Answer 1

In CSS, a ruleset is one of the basic building blocks that make up a stylesheet:

An empty ruleset is one that doesn’t have any property declarations, just a selector:

As you note, these rules don’t have any effect on the rendering of a document, but some browsers will consume them when evaluating CSS only to find nothing there. Performance junkies detest any unnecessary overhead of this sort, so it’s better to scrub them for the sake of cleanliness. In fact, CSS Lint has a rule specifically against empty rulesets, and Code is simply linting your CSS on-the-fly with the same set of rules.

However, empty rulesets can be useful in working around certain browser bugs such as this one. In such situations, removing the empty ruleset actually has adverse effects on page rendering, so they should be left there, ideally with a comment documenting their purpose.

Источник

Visual Studio Code CSS ошибка «не используйте пустые наборы правил»

Я использую Visual Studio Code для HTML и CSS. Я получаю ошибку, которая не ухудшает работу сайта, но я хотел бы узнать о ней больше. Когда я навожу курсор на стиль для ID в HTML, появляется окно с надписью. «Do not use empty rulesets».

Может ли кто-нибудь предоставить дополнительную информацию о «empty rulesets» и объяснить, почему Visual Studio Code (или любой другой редактор) предупреждает о пустом наборе правил?

1 ответ

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

Пустой набор правил-это набор, в котором нет никаких объявлений свойств, только селектор:

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

Похожие вопросы:

Я потратил некоторое время, пытаясь понять, как удалить все пустые строки в Visual Studio Code, и я не могу заставить его работать. Кто-нибудь знает, как это сделать, пожалуйста? Если я ищу ^$ при.

Вчера я опубликовал здесь вопрос ( FxCop и правила анализа кода ) о том, чтобы заставить FxCop запускать те же правила, что и анализ кода, и я думал, что он был решен. Однако, похоже, нет никакого.

Я ищу способ удалить пустые блоки объявления CSS из строки CSS. Поскольку я использую много Sass-миксинов, сгенерированный CSS содержит много правил CSS без объявлений. Чтобы сбрить некоторый размер.

Где я могу найти набор правил, используемых для анализа кода в Visual Studio Express for Desktop 2013? Насколько я понимаю, в экспресс-версиях Visual Studio поддерживается только ограниченный набор.

При включении статического анализа кода в моих сборках я получаю следующую ошибку, вызванную MSBuild: C:\Program файлов (x86)\Microsoft Visual.

Я столкнулся с этой проблемой в Visual Studio Code году. Я уже пробовал переустановить расширение phpcs, но все еще сталкиваюсь с этой проблемой. Не удалось найти phpcs Пожалуйста, добавьте phpcs в.

я использую Visual Studio Code, и у меня есть проблема с переменными в файлах CSS, когда я набираю знак доллара, css файл сообщает об ошибке, и браузер не увидит изменений в файле.

Visual Studio Code не комментирует пустые строки Я искал везде решение этой проблемы, но ничего не мог найти, и это не давало мне покоя уже несколько месяцев. В основном происходит то, что VS Code.

После обнаружения опции Run code analysis on solution в visual studio 2017 я начал искать другие подобные инструменты, я нашел Visual Studio Code Analysis vs StyleCop + FxCop отсюда я узнал о.

Источник

Настройка редактора кода Visual Studio Code

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

Более 5 лет для своей работы я использовал редактор кода Notepad ++, это действительно простая «рабочая лошадка», которая, не смотря на свою простоту,имеет все необходимые базовые функции для написании кода и большой потенциал для расширяемости. Но, как говорится, все когда то заканчивается… Конечно же время не стоит на месте, все развивается, движется вперед, совершенствуется… Чего нельзя, к сожалению, сказать о Notepad++ 🙁 Особенно огорчает дизайн и его привязка к ОС «Windows».

И вот ответ на мою боль — редактор исходного кода «Visual Studio Code»! Современный, бесплатный и кроссплатформенный, созданный в компании Microsoft.

Редактор кода Visual Studio Code

Редактор кода Visual Studio Code

Достоинств у данного редактора достаточно. По мимо подсветки синтаксиса, дизайна, пояснений к набираемому коду и автозавершений, определенным его достоинством является поддержка популярных языков и технологий:

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

Поддержка синтаксиса Emmet

Внимание верстальщики! В «Visual Studio Code» уже включена поддержка Emmet. И вызывается ее исполнение простым нажатием клавиши TAB (табуляция). Для тех кто не в курсе приведу простой пример: что бы нам получить подобную HTML-структуру

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

нам достаточно ввести в документе следующего рода комбинацию и нажать клавишу табуляции, вуаля! И строчка превращается …

div>div>p>ul>li*5

Ну а каркас HTML документа по стандартам W3 HTML5 и подавно создать легко:

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

Освоив не хитрый синтаксис emmet вы определенно сэкономите свое время и нервы при работе с кодом HTML и CSS 🙂 Попробуйте …

Расширения

Как упоминалось выше к данному редактору существует огромное количество расширений, которые что то добавляют, что то меняют в нем… Я приведу лишь ту малую часть, которая полезна в моей работе, а это:

Этого вполне достаточно чтобы вести продуктивную работу фрондэнд-разработчику, конечно же не учитываю ту мощь, которая уже присутствует в ядре редактора.

Как установить расширение?

Установка происходит проще-простого. Либо из меню интерфейса редактора, где необходимо в разделе расширений ввести ключевое слово и воспользоваться поиском:

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

Либо (для более продвинутых) с помощью комбинации клавиш Ctrl+P и в появившуюся строку поиска необходимо забить ключевое слово, либо прямую ссылку для установки расширения, которую можно найти под каждым расширением на его странице, на сайте редактора «Visual Studio Code»:

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

При помощи специальных команд, в строке поиска можно осуществить фильтрацию к вашим расширениям по :

А вообще автоматическое обновление Ваших расширений можно настроить достаточно просто с помощью одной строчки конфигурации. Для этого необходимо открыть настройки редактора:

Файл → Параметры → Параметры пользователя

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

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

Пользовательская настройка редактора

В своем предыдущем редакторе Notepad++ я определенно привык к двум вещам:

Все это мгновенно настраивается. Ниже приведен список настроек редактора с комментариями. Ознакомьтесь на досуге.

Источник

Do not use empty rulesets что это

The best way to learn about happinness-scss is to just install it and give it a try on your code

Use double quotes in attribute values.

Use none keyword for disable border or 0 for border-width property.

Use 1tbs brace style.
Single line are disallowed.

Use hyphenatedbem convention for class names.
Leading underscore is allowed for no-namespace modifiers / utils / helpers (name them as you like)

Clean Import Paths

Files paths should not have leading underscores and should not have filename extensions

Declarations Before Nesting

Declarations should be written before nesting in a ruleset!

Parentheses should be included even if no arguments are defined or used, when declaring or invoking a mixin

Empty Line Between Blocks

Nested blocks should include a space between the last non-comment declaration.
Single line rulesets are disallowed

Extends Before Declarations

Extends should be written before declarations in a ruleset!

Extends Before Mixins

Extends should come before mixins!

Files must end with a new line

Force Attribute Nesting

Use nesting of attributes

Force Element Nesting

Use nesting of elements

Force Pseudo Nesting

Function Name Format

Use hyphenatedlowercase convention for function names.
Leading underscore is allowed.

Rule is disabled in accordance with the ban on the use of identifiers. See No IDs.

Max File Line Count

File»s length doesn’t exceed a 500 number of lines.

Use hyphenatedlowercase convention for mixin names.
Leading underscore is allowed.

Mixins Before Declarations

Mixins should be written before declarations in a ruleset.
Exception [breakpoint, mq, media, clearfix]

No Attribute Selectors

Attribute selectors are allowed.

Hexadecimal colors are allowed.

Colors keywords are allowed, relax since v5.1.0.

Color literals are allowed.

Combinators are allowed.

@debug statements are disallowed to be used.

No Disallowed Properties

Do not use of properties:

No Duplicate Properties

Duplicate properties are disallowed within the same block.
Exception [display]

Empty rulesets are disallowed.

All extends are allowed to be used. Except IDs, see No IDs.

ID selectors are not allowed to be used

!important declarations are not allowed to be used

Only valid of hexadecimal values are allowed.

No Mergeable Selectors

Selectors aren»t repeated and that their properties are merged.

No Misspelled Properties

Correct spelling of CSS properties and prevent the use of unknown CSS properties.

No Qualifying Elements

Qualifying Elements are allowed. Except IDs, see No IDs.

No Trailing Whitespace

Trailing whitespace is not allowed.

Trailing zeros is not allowed.

Keyword all cannot be used with the transition or transition-property property.

The value «all» can have an unpredictable result, which can affect properties that should not be animated. Also this value can affect the performance of your animations.

No Universal Selectors

* (universal) selectors is not allowed.

Domains are not used within urls.

This option is scheduled to be deprecated in favour of the no-url-domains rule in sass-lint 2.0.

No Vendor Prefixes

Vendor prefixes are not allowed to be used.

@warn statements are disallowed to be used.

One Declaration Per Line

New declarations must begin on new lines.

Placeholder in Extend

All extends are allowed to be used. Except IDs, see No IDs.

Placeholder Name Format

Use hyphenatedlowercase convention for placeholder names. Leading underscore is allowed.

Property Sort Order

Order in which declarations are written is disabled

The following CSS units are allowed:

Use shorthand values

Single Line Per Selector

Selectors should be placed on a new line.

Space expected after : are required.

Commas should be followed by a space.

Space Around Operator

Space around operator are required

Space Before Brace

Whitespace required before <

Space Before Colon

No space allowed before :

Space Between Parens

Last declaration in a block should include a semicolon

The W3C says quotes are optional, all three of your ways are legal.

Opening and closing quote just need to be the same character.

If you have special characters in your URL, you should use quotes or escape the characters (see below).

The format of a URI value is ‘url(‘ followed by optional white space followed by an optional single quote (‘) or double quote («) character followed by the URI itself, followed by an optional single quote (‘) or double quote («) character followed by optional white space followed by ‘)’. The two quote characters must be the same.

Escaping special characters:

Some characters appearing in an unquoted URI, such as parentheses, white space characters, single quotes (‘) and double quotes («), must be escaped with a backslash so that the resulting URI value is a URI token: ‘(‘, ‘)’.

Variable For Property

Rule variable-for-property will enforce the use of variables for the values of specified properties. There are no properties by default, except for reserved words listed below which are always whitelisted:

Variable Name Format

Use hyphenatedlowercase convention for variable names.
Leading underscore is allowed.

Источник

Приводим CSS стили к единому и красивому формату

Установка CSScomb, дополнения для Sublime Text 3, которое позволяет привести CSS код к единому стилю.

Устанавливаем CSSComb для Sublime через Package Control: Insall Package.

По умолчанию CSSComb группирует свойства CCS по типу:

Do not use empty rulesets что это. Смотреть фото Do not use empty rulesets что это. Смотреть картинку Do not use empty rulesets что это. Картинка про Do not use empty rulesets что это. Фото Do not use empty rulesets что это

Но например, линтеру SublimeLinter-csslint не нравится всё кроме алфавитного порядка CSS. Да я и сам пришел к выводу, что это намного удобнее.

Так что вот мои настройки CSSComb, которые упорядочивают CSS в алфавитном порядке:

<
// If plugin has trouble finding Node.js, replace this string with path
// to your `node` bin
«node-path» : «:/usr/local/bin»,

// Full list of supported options and acceptable values can be found here:
// https://github.com/csscomb/csscomb.js/blob/master/doc/options.md
«config»: <

// Whether to add a semicolon after the last value/mixin.
«always-semicolon»: false,

// Set indent for code inside blocks, including media queries and nested rules.
«block-indent»: » «,

// Unify case of hexadecimal colors.
«color-case»: «lower»,

// Whether to expand hexadecimal colors or use shorthands.
«color-shorthand»: false,

// Unify case of element selectors.
«element-case»: «lower»,

// Add/remove line break at EOF.
«eof-newline»: false,

// Add/remove leading zero in dimensions.
«leading-zero»: false,

// Unify quotes style.
«quotes»: «single»,

// Remove all rulesets that contain nothing but spaces.
«remove-empty-rulesets»: false,

// Set space after `:` in declarations.
«space-after-colon»: » «,

// Set space after combinator (for example, in selectors like `p > a`).
«space-after-combinator»: » «,

// Set space after ` <`.
«space-after-opening-brace»: «\n»,

// Set space after selector delimiter.
// Новая строчка перед каждым элементом, можно сделать в строку
«space-after-selector-delimiter»: «\n»,

// Set space before `>`.
«space-before-closing-brace»: «\n»,

// Set space before `:` in declarations.
«space-before-colon»: «»,

// Set space before combinator (for example, in selectors like `p > a`).
«space-before-combinator»: » «,

// Set space before ` <`.
// Устанавливает пробел между элементом и скобкой
«space-before-opening-brace»: » «,

// Set space before selector delimiter.
«space-before-selector-delimiter»: «»,

// Set space between declarations (i.e. `color: tomato`).
«space-between-declarations»: «\n»,

// Whether to trim trailing spaces.
«strip-spaces»: false,

// Whether to remove units in zero-valued dimensions.
«unitless-zero»: false,

// Whether to align prefixes in properties and values.
«vendor-prefix-align»: false,

// Sort properties in particular order.
«sort-order»: [
«-moz-animation»,
«-moz-animation-delay»,
«-moz-animation-direction»,
«-moz-animation-duration»,
«-moz-animation-iteration-count»,
«-moz-animation-name»,
«-moz-animation-play-state»,
«-moz-animation-timing-function»,
«-moz-background-clip»,
«-moz-background-size»,
«-moz-border-image»,
«-moz-border-image-outset»,
«-moz-border-image-repeat»,
«-moz-border-image-slice»,
«-moz-border-image-source»,
«-moz-border-image-width»,
«-moz-border-radius»,
«-moz-border-radius-bottomleft»,
«-moz-border-radius-bottomright»,
«-moz-border-radius-topleft»,
«-moz-border-radius-topright»,
«-moz-box-shadow»,
«-moz-box-sizing»,
«-moz-hyphens»,
«-moz-tab-size»,
«-moz-text-align-last»,
«-moz-transform»,
«-moz-transform-origin»,
«-moz-transition»,
«-moz-transition-delay»,
«-moz-transition-duration»,
«-moz-transition-property»,
«-moz-transition-timing-function»,
«-moz-user-select»,
«-ms-animation»,
«-ms-animation-delay»,
«-ms-animation-direction»,
«-ms-animation-duration»,
«-ms-animation-iteration-count»,
«-ms-animation-name»,
«-ms-animation-play-state»,
«-ms-animation-timing-function»,
«-ms-background-position-x»,
«-ms-background-position-y»,
«-ms-filter:\’progid:DXImageTransform.Microsoft.Alpha»,
«-ms-filter:\’progid:DXImageTransform.Microsoft.gradient»,
«-ms-interpolation-mode»,
«-ms-overflow-x»,
«-ms-overflow-y»,
«-ms-text-align-last»,
«-ms-text-justify»,
«-ms-text-overflow»,
«-ms-transform»,
«-ms-transform-origin»,
«-ms-transition»,
«-ms-transition-delay»,
«-ms-transition-duration»,
«-ms-transition-property»,
«-ms-transition-timing-function»,
«-ms-user-select»,
«-ms-word-break»,
«-ms-word-wrap»,
«-ms-writing-mode»,
«-o-animation»,
«-o-animation-delay»,
«-o-animation-direction»,
«-o-animation-duration»,
«-o-animation-iteration-count»,
«-o-animation-name»,
«-o-animation-play-state»,
«-o-animation-timing-function»,
«-o-background-size»,
«-o-border-image»,
«-o-border-image-outset»,
«-o-border-image-repeat»,
«-o-border-image-slice»,
«-o-border-image-source»,
«-o-border-image-width»,
«-o-tab-size»,
«-o-transform»,
«-o-transform-origin»,
«-o-transition»,
«-o-transition-delay»,
«-o-transition-duration»,
«-o-transition-property»,
«-o-transition-timing-function»,
«-webkit-animation»,
«-webkit-animation-delay»,
«-webkit-animation-direction»,
«-webkit-animation-duration»,
«-webkit-animation-iteration-count»,
«-webkit-animation-name»,
«-webkit-animation-play-state»,
«-webkit-animation-timing-function»,
«-webkit-background-clip»,
«-webkit-background-size»,
«-webkit-border-bottom-left-radius»,
«-webkit-border-bottom-right-radius»,
«-webkit-border-image»,
«-webkit-border-image-outset»,
«-webkit-border-image-repeat»,
«-webkit-border-image-slice»,
«-webkit-border-image-source»,
«-webkit-border-image-width»,
«-webkit-border-radius»,
«-webkit-border-top-left-radius»,
«-webkit-border-top-right-radius»,
«-webkit-box-shadow»,
«-webkit-box-sizing»,
«-webkit-hyphens»,
«-webkit-text-align-last»,
«-webkit-transform»,
«-webkit-transform-origin»,
«-webkit-transition»,
«-webkit-transition-delay»,
«-webkit-transition-duration»,
«-webkit-transition-property»,
«-webkit-transition-timing-function»,
«-webkit-user-select»,
«animation»,
«animation-delay»,
«animation-direction»,
«animation-duration»,
«animation-iteration-count»,
«animation-name»,
«animation-play-state»,
«animation-timing-function»,
«background»,
«background-attachment»,
«background-clip»,
«background-color»,
«background-image»,
«background-origin»,
«background-position»,
«background-position-x»,
«background-position-y»,
«background-repeat»,
«background-size»,
«border»,
«border-bottom»,
«border-bottom-color»,
«border-bottom-left-radius»,
«border-bottom-right-radius»,
«border-bottom-style»,
«border-bottom-width»,
«border-collapse»,
«border-color»,
«border-image»,
«border-image-outset»,
«border-image-repeat»,
«border-image-slice»,
«border-image-source»,
«border-image-width»,
«border-left»,
«border-left-color»,
«border-left-style»,
«border-left-width»,
«border-radius»,
«border-right»,
«border-right-color»,
«border-right-style»,
«border-right-width»,
«border-spacing»,
«border-style»,
«border-top»,
«border-top-color»,
«border-top-left-radius»,
«border-top-right-radius»,
«border-top-style»,
«border-top-width»,
«border-width»,
«bottom»,
«box-decoration-break»,
«box-shadow»,
«box-sizing»,
«caption-side»,
«clear»,
«clip»,
«color»,
«content»,
«counter-increment»,
«counter-reset»,
«cursor»,
«display»,
«empty-cells»,
«filter:progid:DXImageTransform.Microsoft.Alpha(Opacity»,
«filter:progid:DXImageTransform.Microsoft.AlphaImageLoader»,
«filter:progid:DXImageTransform.Microsoft.gradient»,
«flex-align»,
«flex-direction»,
«flex-order»,
«flex-pack»,
«float»,
«font»,
«font-effect»,
«font-emphasize»,
«font-emphasize-position»,
«font-emphasize-style»,
«font-family»,
«font-size»,
«font-size-adjust»,
«font-smooth»,
«font-stretch»,
«font-style»,
«font-variant»,
«font-weight»,
«height»,
«hyphens»,
«left»,
«letter-spacing»,
«line-height»,
«list-style»,
«list-style-image»,
«list-style-position»,
«list-style-type»,
«margin»,
«margin-bottom»,
«margin-left»,
«margin-right»,
«margin-top»,
«max-height»,
«max-width»,
«min-height»,
«min-width»,
«nav-down»,
«nav-index»,
«nav-left»,
«nav-right»,
«nav-up»,
«opacity»,
«outline»,
«outline-color»,
«outline-offset»,
«outline-style»,
«outline-width»,
«overflow»,
«overflow-x»,
«overflow-y»,
«padding»,
«padding-bottom»,
«padding-left»,
«padding-right»,
«padding-top»,
«pointer-events»,
«position»,
«quotes»,
«resize»,
«right»,
«tab-size»,
«table-layout»,
«text-align»,
«text-align-last»,
«text-decoration»,
«text-emphasis»,
«text-emphasis-color»,
«text-emphasis-position»,
«text-emphasis-style»,
«text-indent»,
«text-justify»,
«text-outline»,
«text-overflow»,
«text-overflow-ellipsis»,
«text-overflow-mode»,
«text-shadow»,
«text-transform»,
«text-wrap»,
«top»,
«transform»,
«transform-origin»,
«transition»,
«transition-delay»,
«transition-duration»,
«transition-property»,
«transition-timing-function»,
«user-select»,
«vertical-align»,
«visibility»,
«white-space»,
«width»,
«word-break»,
«word-spacing»,
«word-wrap»,
«z-index»,
«zoom»
]
>
>

Результат алфавитного упорядочивания CSS стилей с помощью CSS Combo:

Источник

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

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