Use of important ошибка

Почему ваши CSS-правила иногда не работают, зачем на самом деле нужен !important и как работает каскад CSS — рассказываем в статье.

Когда CSS-правило не работает, многие разработчики хотят добавить !important и забыть о проблеме. Рассказываем, почему так делать не стоит и как правильно работать с CSS.

Когда браузер загружает веб-страницу, он собирает все CSS-правила, которые встречает: из внешних файлов, напрямую указанные в HTML-коде, добавленные с помощью JS. У каждого правила есть селектор, которые говорит к каким HTML-элементам его надо применять. Часто так случается, что один и тот же элемент получает не одно правило, а два и больше. И иногда эти правила даже относятся к одним и тем же свойствам.

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

Так как понять, какое CSS-правило «главнее»?

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

Но вернёмся к !important. Это магическое слово сразу же поднимет приоритет вашего CSS-правила до небес. Но так всё равно лучше не делать, потому что:

  • так код сложнее поддерживать (если с вашим кодом будет работать человек, который знает, как строится каскад стилей, он не сможет ничего нормально написать как бы ни старался),
  • надо постоянно использовать !important и дальше.

Зачем же всё таки иногда нужен !important?

  • Чтобы переписать inline-свойства. Нужно редко, но иногда пригождается.
  • Чтобы переписать !important сторонней библиотеки. Если её разработчик по какой-то причине его использовал. Возможно как раз потому, что не понимал каскад.
  • Для прототипирования. Чтобы быстро прописать новые стили, вывести их наверх каскада, посмотреть результат и если всё устраивается — переписать правильно.

Как работает каскад CSS?

Общий принцип прост: «Чем специфичнее правило — тем выше оно в каскаде». Например, у нас на сайте в списке статей на главной каждый пост — это контейнер с классом box. У него прописан стиль

.box {
    box-shadow: 0 0 0 1px rgba(0,0,0,.05);
}

Это правило добавляет красивую рамку. Но в тёмной теме это бессмысленно, ибо на тёмном фоне тёмная рамка не нужна. В тёмной теме и так достаточно контраста.

Мы добавили правило

.dark .box {
    box-shadow: initial;
}

И прописали у тега body (родительский тег для всего контента вообще на сайте) класс dark.

В итоге второе правило более специфично, оно даёт путь из двух компонент. И применяется именно оно, перекрывая предыдущее. То есть в тёмной теме рамки у постов нет.

Каскад CSS

1. Важность

Первая ступень каскада рассматривает тип правила.

Есть четыре уровня типов:

  1. transition (переход). Правила, которые применяются к активному переходу, имеют первостепенную важность.
  2. !important. Если поставить !important в конце правила, оно перейдёт на этот уровень каскада. В идеале вы должны использовать !important только для переопределения inline-стилей или других !important из сторонних библиотек.
  3. animation (анимация). Правила, применяющиеся к активной анимации, повышают уровень в каскаде.
  4. normal. На этом уровне находится основная часть правил.

Как видите, эти типы обеспечивают корректную анимацию элементов. Если оба правила относятся к одному уровню, приоритет определяется на другой ступени каскада.

2. Происхождение

Вторая ступень смотрит, где определено правило.

Таких мест может быть три (расположены в порядке приоритета):

  1. Веб-сайт. Единственный уровень, который вы можете контролировать как веб-разработчик.
  2. Пользователь. Стили, которые пользователь подключает через настройки браузера.
  3. Браузер. У каждого браузера есть свой набор стилей — например элемент <button> всегда использует стиль браузера по умолчанию.
    Так выглядит кнопка в вашем браузере

Примечание Важно! Иерархия для правил с !important здесь работает наоборот: !important-правило браузера выигрывает у !important-правила веб-сайта, тогда как обычные правила сайта превосходят правила браузера.

3. Специфичность

На третьей ступени важна специфичность правила. Значение специфичности определяется исходя из уровней селекторов CSS.
Всего уровней четыре:

  1. inline. Стили, объявленные в HTML-свойстве style, обладают наибольшей специфичностью.
  2. id. Можно использовать идентификатор (синтаксис #id) для определения стиля конкретного элемента.
  3. класс | атрибут | псевдокласс. Определять стиль элемента также позволяют классы (синтаксис .class). Этот уровень включает селекторы HTML-атрибутов, например [checked] или [href="https://wattenberger.com"], и псевдоклассы, такие как :hover и :first-of-type.
  4. тип | псевдоэлемент. Тип тега (синтаксис type) тоже используется для определения стиля элементов. Сюда же входят псевдоэлементы вроде :before и :selection.

Стоит отметить, что здесь имеет значение число «вхождений» в какой-либо уровень.

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

4. Позиция

Последняя ступень каскада смотрит на порядок определения правил.

Всегда побеждает то правило, которое объявлено позже (при условии, что всё остальное в каскаде одинаково).

***

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

А теперь небольшой тест: как думаете, какое из двух правил победит?


На основе «The CSS Cascade»

When styling elements with CSS, sometimes we can get frustrated that the styling is not applied and using the !important rule can force a CSS snippet to work.
We can use this to force a CSS style. It sometimes work as a quick fix but not always.

This post will go through reasons why using the !important CSS keyword might not be working for you
and their fixes.

The common reasons why !important is not working comes down to:

  1. You are using the wrong CSS selector and not targeting the correct element,
  2. You are using in animation @keyframes
  3. Using !important multiple times and having conflicts

What is the !important keyword?

The !important rule have been around since CSS1 specification in 1991 and allows the user to overrride browser specificity — this just means how a browser
will decide which style to apply to each element.

The following diagram shows how browser will render HTML and display it to the user

image of how browser rendering works

Consider the following CSS style where we want to make all fonts in the <blockquote> to be italic:

blockquote * {
    font-style: italic;
}

Now if somehow the above is not working, we can use the !important rule like so:

blockquote * {
    font-style: italic !important; /* Adding important to increase specifity */
}

CSS Specifity — which style gets applied!

CSS specifity just refers to which style the browser will apply to each element. There are quirks amongs browsers but most modern browsers like Chrome, Edge, Safari,
etc generally follow the same rules.

Browsers will use the following order when deciding to apply a style to a specific element — lower down the list gets the highest precedence:

  • Browser Styles — each browser (chrome, safari, etc) comes with their own stylesheets. These default styles applied by your browser with the least precedence.
  • User Styles — Custom styles created by the brower’s user.
  • Author Styles — Styles created by the author/ creator of the website or page.
  • !important Author Styles — author styles declared with important keyword.
  • !important User Styles — user styles declared with important keyword.
  • Inline Styles — inline styles will be given highest precedence and overwrite any styles previously.

Within each of the CSS stylesheets, it then follows the below order — lower down the list is given the most specifity:

  • * — wildcard selector
  • Type Selectors e.g <p> and Pseudo Elements e.g ::after
  • Class Selectors e.g. .container , Attributes Selectors e.g. [target=”_blank”] and Pseudo Classes e.g. :hover.
  • ID Selectors e.g. #app
  • Inline styles
  • !important — this will override any other previous styles

Fix 1 — !important not targetting correct element

The most common reason why using !important CSS rule is not working to style your element is that it is not targetting the correct element.

As an example, consider the following HTML and CSS

<div class="ui-tabs">
    <ul>
        <li class="ui-active">
            <a href="#">Text</a>
        </li>
    </ul>
</div>
.ui-tabs .ui-active {
    background: #084;
    color: blue !important;
}

a:link {
    color: red;
}

Now we can see that that text link <a> is not blue — even though we applied the !important rule to it. The reason this is failing is because we applied the rule
to the wrong element. From the above, we have applied the color blue the list item elements and not link elements.

If we change the CSS to the following:

.ui-tabs .ui-active a:link {
    background: #084;
    color: blue !important;
}

a:link {
    color: red;
}

This will target the link <a> inside the list item <li> element

Fix 2 — !important used in @keyframes

One reason that the !important rule would not work is it only works on cascade properties. The cascade is how browers determine styles from different sources are combined
to be applied for a specific element.

At rules such as the @keyframes do not participate in the cascade and therefore using !important will not work!

As example, consider the following HTML

<div id="mydiv" style="margin-left: 5px"></div>

We then want to animate this <div> using @keyframes as follows:

#mydiv {
    width: 100px;
    height: 100px;
    animation: animateLeft 4s infinite ease-in 1s
}

@keyframes animateLeft {
    0% {
        margin-left: 100px!important
    }
    100% {
        margin-left: 500px
    }
}

The above margin-left: 100px!important will not work, because @keyframes does not interact with the cascade and therefore the margin-left style of the <div> will not be overwritten by the value inside the 0%.

It will stay the same style as the inline style margin-left: 5px. If we remove the !important, then the margin-left: 100px; will be enforced!

#mydiv {
    width: 100px;
    height: 100px;
    animation: animateLeft 4s infinite ease-in 1s
}

@keyframes animateLeft {
    0% {
        margin-left: 100px;
    }
    100% {
        margin-left: 500px
    }
}

💡 Tip — dont use !important in @keyframes!

More information located here:
https://www.w3.org/TR/css-animations-1/#keyframes

Fix 3 — !important used multiple times

The !important rule can be used to override an element’s styles, but it could be used to be overritten by itself. This can happen when you have multiple !important rules
with the same selectors. Consider the following CSS style:

img { border: none !important; }
#article img { border: 2px solid #fff !important; } /* This will be applied*/

The bottom rule that specifies a border around the image will be applied because it has a higher specifity than the more generic top rule!

💡 Tip — matching selectors that are declared lower in the CSS document will take precedence

One thing to keep in mind is that when you have multiple selectors that select the same element, the selector that is at the bottom of the CSS document will be applied!
So for example, lets say we have the following paragraphs and their styles:

<div>
    <p>First paragraph</p>
</div>
<p>First paragraph</p>
p { color: red; }
p { color: blue; }

In the above, all <p> paragraph elements will have text of blue color! Even though we have two matching selectors, CSS style that is lower in the document will take precedence!
To get around this and make the first paragraph color red, we can bump up the specifity declaring the following:

div p { color: red; }
p { color: blue; }

When should you use !important

Best practice is to avoid using !important and use specifity rules instead. This will make your CSS much cleaner and easier to manage. For example, too many important rules
will make you loose track of which one is more important than the other (given the same selector).

However, the important rule can be handy and useful in some use cases:

  • Used with user styles to apply the user custom CSS they want to apply for a webpage. This is because we have no control over the CSS that has been loaded.
  • Dynamic styles set by JavaScript — to override styles applied by JS on the fly

Browser support

!important has been part of the CSS spec ever since CSS1 in 1991 and browser support for this is good for most modern browsers (chrome, safari, firefox, etc) and even older browsers such as IE (Internet explorer)

Summary

In this post I went over how CSS !important is not working — this can be a quick fix, but not recommended approach!

A checklist of how to troubleshoot why !important is not working is:

  1. Check that the !important property is applied correctly to the target element.
  2. Determine if the !important is used in at-rules such as @keyframes. This will not work because @keyframes will ignore the cascade
  3. Check that important is not used multiple times with your CSS — for example a higher specifity CSS declaration with !important applied will override anything that is less specific

!important CSS rules exist to be broken, or at least that’s the idea behind this property to make possible to override other previous styles

Updated on August 4, 2022

All About !Important CSS Rule

CSS rules were made to be broken, or that’s the idea behind !Important. This !important CSS rule and property makes it possible to override other previous styles spread across multiple style sheets. !important essentially defines something as important. Imagine that! Ignoring subsequent/conflicting rules. It makes the CSS style with the !important designation the one that counts most, nullifying any others. Essentially, it gives a CSS value more weight than it would generally have.

!important was introduced with the CSS1 specifications in the mid-to-late-1990s. Since then, !imporant has mainly remained unchanged (only one change in CSS2.1. And is either a bane or boon depending on whether you’re using it or debugging its use.

Using !Important CSS Rule & Property

Important is fairly straightforward as far as use. This example code snippet can help you to understand formatting:

p {
font-size: 12px !important; }

!important comes after a CSS declaration, but before the ending semicolon. A space before the semicolon won’t break it. So long as !important is up as such at the end of the line.

Sorting and Overriding CSS Rules

!important influences sorting according to importance and origin. According to W3C, the ascending order of precedence is:

  1. User-agent declarations
  2. User normal declarations
  3. Author normal declarations
  4. Author important declarations
  5. User important declarations

Confused yet? You’re not the only one. At this point, it’s (!)important to also take note of limitations. Browser Support for !important exists on IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.

Overriding CSS rules are hard to follow.

More specific CSS rules tend to override less-specific CSS rules. For example, the basic, Lessspecific:

Is overruled by the More specific:


#container h2 {
font-size: 14px; }

Of course, if you were to apply !important to the former, it would work to override the latter.

In the case where two CSS declarations have the same weight, order, and specification, it’s later that overrules all else.

Furthermore, according to Smashing Magazine, If !important is used on a shorthand property, this adds “importance” to all the sub-properties that the shorthand property represents.

Should You !Important CSS Rule & Property?

Should You Use !important?
All About !Important CSS Rule

CSSTricks makes a case for using !important for utility classes but decries its use in almost any other situation.

!important could be ethically present as a temporary fix to an urgent issue. Though it should not be the end of a project. Once the critical problem is fixed, pains should be ready to dig back into the code and fix it without using this CSS declaration. Alternatively, a browser inspector tool might be able to help you determine and fix an issue—without the use of !important.

A final use case possibility for !important lies in pages or blog posts that require unique styles. As with the case for improving accessibility, this solution would only affect certain pieces and not the general version of the website as a whole.

The main issue with using !important is that it is hard to debug CSS issues, especially when passing code from one developer to another. If you’ve ever been ready to pull your hair out because you couldn’t figure out what exactly is causing a specific style, it probably resulted from the lazy use of !important.

Devs

Most developers are publicly against !important, but its private use is what ultimately causes these numerous debugging issues. More often than not, instead of finding the root of the problem, additional !important rules are implemented, further muddying the code. When it comes to !important, would you rather be the person to cause and continue a problem or the one to fix it?

continue a problem or the one to fix it?
All About !Important CSS Rule

20 November, 2012

Written by on CSS Wizardry.

Table of Contents

  1. Undoing styles
  2. Magic numbers
  3. Qualified selectors
  4. Hard-coded/absolute values
  5. Brute forcing
  6. Dangerous selectors
  7. Reactive !important
  8. IDs
  9. Loose class names
  10. Final word

Chris Coyier recently answered someone’s question:

How can you tell if your CSS code smells? What are the signs that the code is sub-optional, or that the developer hasn’t done a good job? What do you look for in the code to determine how good or bad it is?

I thought I would extend Chris’ great answer with my own, additional take on things…

My day-to-day life is spent working in-house at BSkyB… I work on big websites, the last of which took me over a year to build the front-end for (and it’s still ongoing). For me, in my world, bad CSS is a very specific and troublesome thing; when you’re working on one site for months on end, you can’t afford poor code, be it CSS or otherwise, and any bad code needs righting.

I’m going to share just a few things (there will, no doubt, be things that I have missed) that I look out for in CSS that will give you and idea as to its quality, its maintainability and its integrity…

Undoing styles

Any CSS that unsets styles (apart from in a reset) should start ringing alarm bells right away. The very nature of CSS is that things will, well, cascade and inherit from things defined previously. Rulesets should only ever inherit and add to previous ones, never undo.

Any CSS declarations like these:

border-bottom: none;
padding: 0;
float: none;
margin-left: 0;

…are typically bad news. If you are having to remove borders, you probably applied them too early. This is really hard to explain so I’ll go with a simple example:

h2 {
    font-size: 2em;
    margin-bottom: 0.5em;
    padding-bottom: 0.5em;
    border-bottom: 1px solid #ccc;
}

Here we’re giving all h2s our usual font-size and margin for spacing, but also a bit of padding and a keyline on the bottom edge to visually separate it from the next element on the page. But, perhaps we have a circumstance in which we don’t want that keyline, perhaps we have a situation where we want a h2 to not have that border and padding. We’d likely end up with something like this:

h2 {
    font-size: 2em;
    margin-bottom: 0.5em;
    padding-bottom: 0.5em;
    border-bottom: 1px solid #ccc;
}

.no-border {
    padding-bottom: 0;
    border-bottom: none;
}

Here we have ten lines of CSS and one ugly class name. What would have been better is this:

h2 {
    font-size: 2em;
    margin-bottom: 0.5em;
}

.headline {
    padding-bottom: 0.5em;
    border-bottom: 1px solid #ccc;
}

Here we have eight lines of CSS, no undoing anything, and a nice, sensible class name.

As you go down a stylesheet you should only ever be adding styles, not taking away. If you find you are having to undo styling as you go down your document the chances are you jumped the gun and started adding too much too soon.

This was a very timid example, but it helps illustrate my point perfectly. Imagine CSS like this over tens of thousands of lines… that’s a lot of bloat and a lot of unnecessary undoing. Peg things onto simpler things that came before it, do not start too complex and risk having to undo your work later on; you’ll end up writing more CSS to achieve less styling.

As soon as I see CSS that undoes previous styling, I can be pretty sure that it’s because something was poorly architected and that the order in which things were built/written needs a rework.

Magic numbers

These are a particular bugbear of mine. I loathe magic numbers.

A magic number is a value that is used ‘because it just works’. Take the following example:

.site-nav {
    [styles]
}

    .site-nav > li:hover .dropdown {
        position: absolute;
        top: 37px;
        left: 0;
    }

top: 37px; here is a magic number; the only reason it works, presumably, is because the lis inside .site-nav happen to be 37px tall, and the .dropdown flyout menu needs to appear at the bottom of it.

The problem here is that 37px is entirely circumstantial and as such, we should place no faith in that number. What if someone changes the font-size in .site-nav and now everything is 29px tall? This number is no longer valid and the next dev needs to know to update it.

What happens when Chrome does render the lis at 37px, but IE renders it at 36px? That number only works in one situation.

Never, ever use numbers just because they work. In this situation we’d be far better off replacing top: 37px; with top: 100%;, which basically means ‘all the way from the top’.

Magic numbers have several problems associated with them. As above, they cannot be relied upon, but also, with their very ‘just because it works’ nature, it’s difficult to communicate to another dev where that number came from. If you had a more complex example which used a magic number—and that magic number became invalid—you are faced with one or more of the following problems:

  • The next dev doesn’t know where the magic number came from, so they delete it and are back at square one.
  • The next dev is a cautious dev who, because he doesn’t know where the magic number came from, decides to try and fix the problem without touching that magic number. This means that an old, outdated, hacky magic number stays in the code, and the next dev simply hacks away on top of it. You are now hacking on top of a hack.

Magic numbers are bad news; they soon become out of date, they confuse other developers, they cannot be explained, they cannot be trusted.

There’s nothing worse than hitting someone else’s code and seeing an inexplicable number. You’re left wondering what the hell it does, why it’s needed and whether or not you should dare touch it.

As soon as I see magic numbers in CSS I start asking questions. Why is this here? What does it do? Why does that number work? How can you achieve the same without that magic number?

Avoid magic numbers like the plague.

Qualified selectors

Qualified selectors are ones like:

ul.nav {}
a.button {}
div.header {}

Basically, selectors who are needlessly prepended by an element. These are bad news because:

  • They totally inhibit reusability on another element.
  • They increase specificity.
  • They increase browser workload (decreasing performance).

These are all bad traits. Those selectors can, and should be:

.nav {}
.button {}
.header {}

Now I know I can apply .nav to an ol, I can apply .button to an input, and—when the site gets ported over to HTML5—I can quickly swap out my header div for a header element without worrying about invalidating any styles.

With regards performance, this is only a very slight issue, however it is an issue nonetheless. Why make a browser look for a class .button on an a when you could just ask it to look for .button and be done? By qualifying selectors you are increasing a browser’s workload.

More extreme examples might be:

ul.nav li.active a {}
div.header a.logo img {}
.content ul.features a.button {}

All of these selectors can be trimmed down massively, or totally rewritten, to:

.nav .active a {}
.logo > img  {}
.features-button {}

Which will help us:

  • Save actual amounts of code
  • Increase performance
  • Allow greater portability
  • Reduce specificity

As soon as I spot overqualified selectors when I scroll down a stylesheet I instantly want to know why they’re written so verbosely and how we can trim them down to as short as possible.

Hard-coded/absolute values

Not unlike magic numbers, hard-coded values are also bad news. A hard-coded value might be something like this:

h1 {
    font-size: 24px;
    line-height: 32px;
}

line-height: 32px; here is not cool, it should be line-height: 1.333

Line heights should always be set relatively in order to make them more forgiving and flexible. If you ever change the font-size of a h1, you want to know that your line-height will track it. Not having a relative line-height means that if you ever need to modify a h1 you will likely end up with something like this:

h1 {
    font-size: 24px;
    line-height: 32px;
}

/**
 * Main site `h1`
 */
.site-title {
    font-size: 36px;
    line-height: 48px;
}

Here we need to keep on adding fixed line-heights indefinitely as our initial one was never flexible enough. With a unitless and/or relative line-height, we’d have simply needed:

h1 {
    font-size: 24px;
    line-height: 1.333;
}

/**
 * Main site `h1`
 */
.site-title {
    font-size: 36px;
}

This may not seem like a massive difference, but on every text element over a large project, this has a big impact.

N.B. this applies to a lot more than just line-heights; basically any hard-coded absolute in a stylesheet needs treating with caution and suspicion.

Hard-coded values are not very future proof, flexible or forgiving, and thus should be avoided. The only things that should ever really have hard-coded values are things like sprites which will always need to be a certain size no matter what.

As soon as I see a hard-coded unit in a stylesheet I want to know why it was required and how it could be avoided.

Brute forcing

This one is in a similar vein to hard-coded numbers, but a little more specific. Brute forcing CSS is when you use hard-coded magic numbers and a variety of other techniques to force a layout to work. Take for example:

.foo {
    margin-left: -3px;
    position: relative;
    z-index: 99999;
    height: 59px;
    float: left;
}

This is terrible CSS. All of these declarations are heavy-handed, brute-forced, layout-affecting declarations which are clearly only used to force something to render as and where it’s wanted.

This type of CSS is indicative of either a poorly coded layout that requires this kind of manipulation, a lack of understanding of box-model and layout, or both.

Well coded layouts should never need brute-forcing, and a solid understanding of box model, layout and taking a look at your computed styles more often should mean that you’d rarely end up in a situation like this.

As soon as I see brute-forced CSS I want to know how it happened, and how far back we need to unpick things before we can lay things out more rationally.

Dangerous selectors

A ‘dangerous selector’ is one with far too broad a reach. A really obvious and simple example of a dangerous selector might be:

div {
   background-color: #ffc;
   padding: 1em;
}

This will instantly scream at any developer; why on earth would you want to carpet bomb every div on your site? Good question, so why would anyone ever want to have a selector like aside {} for example? Or header {}, or ul {}? Selectors like these are way, way too far reaching and will ultimately lead to us having to undo CSS, as per the section previously.

Let’s look at the header {} example more closely…

A lot of people use a header element to mark up their site’s main header—which is fine—however, if you style that site-wide header like this:

header {
    padding: 1em;
    background-color: #BADA55;
    color: #fff;
    margin-bottom: 20px;
}

…then that’s not so fine. The header element does not mean ‘your site’s main header’ and, as per the spec, the header element can be used multiple times in multiple contexts. This should be targeted via a selector more like .site-header {}, for example.

To give such specific styling to such a generic selector is dangerous. Your styles will leak out into areas they shouldn’t as soon as you start trying to use that element again, and you’ll need to start undoing styles (adding more code to take styles away) in order to combat this.

Make sure your selectors have good selector intent.

Take the following:

ul {
    font-weight: bold;
}

header .media {
    float: left;
}

As soon as I see selectors that end in either a type selector or a very basic abstraction class, as above, I start to panic. I know that these selectors are far too broad and will quickly run us into trouble. As soon as we try and reuse those elements we will find that they’re inheriting styles we don’t necessarily want because, somewhere, there’s a really broad selector managing to reach them.

Reactive !important

!important is fine. It’s fine and it’s a, well, important tool. However, !important should only be used in certain circumstances.

!important should only ever be used proactively, not reactively.

By this I mean that there are times when you know you will always, always want a style to take precedence, and you will know this up front.

For example, you know that you will always want errors to be red, so this rule is totally fine:

.error-text {
    color: #c00!important;
}

If the error occurs in a div where the text is always blue, we can be confident that we want to break that rule in the case of errors. We always want errors to be red because it’s an error, and user messaging should always remain consistent. Here we can proactively add !important because we know we always want errors to be red.

Where !important is bad is when it is used reactively, that is to say, it’s been used to get someone out of a specificity problem, or they’re in a bit of a bind and resort to !important to force things to work. This is using !important reactively and this is bad news.

Using !important reactively is just a way of circumventing the problems caused by ill-formed CSS. It doesn’t fix any problems, it only fixes the symptoms. The problems still exist, but now with and added layer of super-specificity that will take yet more specificity to overcome.

I have no qualms whatsoever with !important, as long as it has been used proactively. As soon as I see reactive use of !important I know right away that it’s likely because of some poorly architected CSS, and that the solution is a refactor, not a hasty addition of heavy-handed specificity.

IDs

This one is very specific to me, and to larger teams. I have written before about how IDs are a bad idea because of their heightened specificity; they are of no use to anyone and should never be used in CSS. Use IDs in HTML for fragment identifiers and JS hooks, but never in CSS.

The reasons are simple:

  • IDs can never be used more than once in a page.
  • Classes can exist only once, or a million times in a page.
  • IDs can often have their traits abstracted out into many reusable classes.
  • An ID is 255 times more specific than one class…
    infinitely more specific than a class.
  • This means you’d need 256 chained classes to override one ID
    no amount of chained classes can override an ID.

If that last bullet point hasn’t convinced you not to use them then I don’t know what will…

As soon as I see an ID in a stylesheet, I want it replaced with a class. Specificity is how projects start to spiral so it is vital to keep it low.

Fun exercise: try elegantly solving this problem. Clue: this isn’t elegant, nor is this.

Loose class names

A ‘loose’ class name is one that isn’t specific enough for its intended purpose. Imagine a class of .card. What does this do?

This class name is very loose, and loose class names are very bad for two main reasons:

  • You can’t necessarily glean its purpose from the class alone.
  • It’s so vague that it could very easily be redefined accidentally by another dev.

The first point is the simplest; what does .card mean? What does it style? Is it a Trello-esque concept where a card is a component? Is it a class that you add to a playing card on a poker website? Does it refer to an image of a credit card? It’s difficult to know, because it’s far too loose. Let’s imagine it means credit card; this class would have been much better had it been .credit-card-image {}. A lot longer, yes; a lot better, hell yes!

The second problem with loose class names is that they can very easily be (accidentally) reassigned/redefined. Let’s say you’re working on an commerce site using .card again, and it refers to the user’s credit card linked to their account. Now imagine another dev comes along and wants to add some functionality whereby you can send a purchase to someone as a present, with the option to add a card with a message on it. Their temptation might be to use .card again somewhere, which is wrong, but in certain (albeit unlikely events) this could lead to your .card class being redefined and overwritten.

All this can be avoided by using much stricter class names. Classes like .card and .user and suchlike are far too loose, making them hard to quickly understand, and easy to accidentally reuse/override.

As soon as I see loose class names I start having to work out what it actually refers to, and asking what we can rename it to. Class names should be as specific as possible.

Final word

So there we have it, just a few of the many things I perceive to be code smells in CSS. These are things that I look out for on a daily basis and strive to avoid at all costs. When working on larger projects that last for months and months (and, ultimately, years) it is vital to keep a tight ship, and keeping an eye out for the above—among other things—is paramount. (I can’t stress enough how small a sub-set of things this is; there is a lot more that I look out for.)

Now, of course, there are exceptions to every rule, but they will need assessing on a case by case basis. For the most part, however, these are all things I work hard to avoid, and can spot a mile off in CSS.



☕️ Did this help? Buy me a coffee!

A ! delimiter followed by the important keyword marks the declaration as important. The !important flag alters the rules selecting declarations inside the cascade. A declaration that is not important is called normal.

To mark a declaration important, add the important flag (!important) after the value in the declaration. While white space is allowed between the delimiter and the keyword, the flag is generally written as !important without any white space.

selector {
  property: value; /* normal declaration */
  property: value !important; /* important declaration (preferred) */
  property: value ! important; /* important declaration (not preferred) */
}

The !important comes after the value of the property value pair declaration, preceded by at least one space. The important flag must be the last token in the declaration. In other words, there can be white space and comments between the flag and the declaration’s ending semicolon, but nothing else.

Impact on the cascade

When it comes to important declarations, the cascade origin and layer orders are reversed. Without the important flag, declarations in the author’s style sheets override declarations in a user’s style sheet, which override declarations in the user-agent’s default style sheet.

When a declaration is important, the order of precedence is reversed. Declarations marked as important in the user-agent style sheets override all important declarations in the user style sheets. Similarly, all important declarations in the user style sheets override all important declarations in the author’s style sheets. Finally, all important declarations take precedence over all animations.

Note: All important declarations take precedence over all animations. !important is not valid within @keyframes animation declarations.

Reversing the precedence order for important declarations ensures users with special needs, such as personalized color schemes or large fonts, can override author styles when needed by marking some declarations in their user’s style sheet as important. It also guarantees malicious extensions can’t override important user-agent styles, which might break functionality or negatively impact security.

Does anything have precedence over important declarations? Yes, transitions. CSS transitions are a way to control the speed at which the property changes from one value to another. While transitioning from one value to another, a property will not match a specific important declaration.

a {
  color: red !important;
  background-color: yellow;
  transition: all 2s linear;
}
a:hover {
  color: blue !important;
  background-color: orange !important;
}

In this example, the color and background-color properties will transition to the hovered state over two seconds. Even though default states are normal declarations and hover states are !important declarations, the transition does happen.

Cascade layers

Within each of the three origins for style sheets – author, user, and user-agent – normal declarations in unlayered styles override layered style declarations, with the last declared having precedence over the layers declared before it. Important declarations reverse the order of precedence: important declarations in the first layer take precedence over important declarations in the next layer, and so on. Also, all the important declarations have precedence over important declarations made outside any layer.

Inline styles

Inline styles are styles defined using the style attributes. They can also be normal or important. Inline normal styles take precedence over all normal declarations, no matter the origin. Inline important styles take precedence over all other important author styles, no matter the layer, but important styles from user’s or user-agent’s style sheets and transitions override them.

!important and specificity

While !important is not part of determining specificity, it is related. Important declarations override all other declarations from the same origin and cascade layer.

#myElement#myElement#myElement .myClass.myClass p:hover {
  color: blue;
}

p {
  color: red !important;
}

This example displays a case of over-specifying a selector. No matter how high the selector specificity matches a normal declaration, an important declaration from the same source and cascade layer will always have precedence. In this case, the paragraph will always be red.

When two important declarations from the same origin and layer apply to the same element, browsers select and use the declaration with the highest specificity.

#myElement p {
  color: green !important;
}

p {
  color: purple !important;
}

In this case, the selector specificity matters. Only if the selectors had the same specificity would source order matter.

Impact on shorthand properties

Declaring a shorthand property with !important sets all of sub-properties as important. To two following selector style blocks are equivalent:

p {
  background: blue !important;
}

p {
  background-image: none !important;
  background-position: 0 0 !important;
  background-size: auto auto !important;
  background-repeat: repeat !important;
  background-origin: padding-box !important;
  background-clip: border-box !important;
  background-attachment: scroll !important;
  background-color: blue !important;
}

This example shows one of the several reasons avoiding the important flag is generally recommended.

Impact on custom properties

When the !important flag is added to a custom property value declaration, it makes the value assignment important. The !important flag is then stripped from the custom property value. The !important flag is not passed as part of the custom property value to the var() function.

:root {
  --myColor: red !important;
  --myColor: blue;
}
p {
  color: var(--myColor);
  }
blockquote {
   color: var(--myColor);
   color: purple;
}
<p>This is a paragraph</p>
<blockquote>This is a blockquote</blockquote>

In this example, the paragraph will be red, not blue, as the custom property value assignment is important. The blockquote will be purple, because the purple normal declaration comes after the normal red declaration.

Best practices

Avoid using !important to override specificity. When intentionally creating important declarations for UI requirements, comment in your CSS code to explain to maintainers why they should not override that feature.

Even when working to override high-specificity styles not under your control, such as styles in a 3rd party plugin declared with an id selector, you don’t need to use !important. Consider instead importing the 3rd party stylesheet script into a named or anonymous layer as your first cascade layer, instead of using !important. As long as the external styles do not include important declarations, your styles will take precedence over the widget styles, no matter the specificity.

If you need to override an external stylesheet containing important declarations, create a cascade layer containing the needed overrides, and declare that layer first.

Accessibility

Important styles from a user stylesheet take precedence over the author style sheet’s important declarations, meaning adding an !important flag to a site’s styles will not prevent individual users with special requirements, such as large fonts, from being able to override your styles by adding important styles in their own user’s style sheet.

Browser compatibility

This feature is supported in all browsers.

See also

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

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

Правило с !important само по себе не обращает внимания на специфику или каскадирование. Поведение зависит от контекста, но практически всё в CSS может быть перезаписано с !important.

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

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

Говоря о специфичности, мы имеем ввиду более точный селектор, как в следующем примере:

.entry-content {
    color: red;
}

.entry-content p {
    color: black;
}

Последнее правило более точное, так как мы выбрали <p> элементы внутри .entry-content, следовательно <p> теги будут черного цвета.

Менее специфичные селекторы это типовые селекторы (h1pspandiv), следующие за классовыми селекторами (.entry-content), селекторами атрибутов (type='radio') и псевдоклассами(:hover:focus). Самые весомые в этом случае это ID селекторы (#main).

Под каскадированием мы подразумеваем естественный каскадный поток CSS. Где по важности находится правило? Чем оно ближе к концу в цепочке правил, тем больше важности оно имеет. Порядок таков: объявления из браузера, затем от пользователя, затем от автора, затем от автора с !important, затем от пользователя с !important. Если у браузера есть дефолтный стиль для тегов заголовков, то вы как автор легко можете перезаписать его с селекторами меньшей специфичности. И мы еще не упоминали наследование, которое случается довольно часто.

Конечно же, такое каскадирование тоже работает в таблице стилей: более позднее правило с той же специфичностью побьёт предыдущее.

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

И так, для чего мы можем его использовать?

Безусловно !important имеет плохую репутацию, так как иногда для ленивых разработчиков — особенно для меня — гораздо удобнее перезаписать всё с помощью этого не совсем элегантного способа, вместо того, чтобы копаться в коде и решать реальную проблему, которая обычно кроется в плохой архитектуре.

Дебажиим код

Самый очевидный способ использовать это слово — это дебаггинг вашего кода, обычно в браузере. Временно используя !important в вашем коде, вы можете устранить некоторые конфликты и можете изолировать проблему. В Chrome, вы можете также добавить инлайновые стили, которые также переписывают необходимые авторские значения.

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

Скрытие элементов

Есть разные способы что-нибудь спрятать от обычных пользователей, но если вы хотите точно убедиться в результате, то !important может быть полезным. Конечно, если вы работаете над своим проектом, вы знаете точно — так ли это вам нужно.

.visually-hidden {
    position: absolute !important;
    height: 1px; width: 1px; 
    overflow: hidden;
    clip: rect(1px 1px 1px 1px); 
    clip: rect(1px, 1px, 1px, 1px);
}

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

Защитный CSS

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

.entry-content img {
    display: block !important;
}

Используя этот коды вы убедитесь в том, что пользователь по ошибке не сможет сделать изображение строчным или строчно-блочным , даже если теоретически может.

Хакнуть восхитительный WYSIWYG редактор

В WordPress стандартным WYSIWYG редактором является TinyMCE, который по моему мнению не самый худший. Один из его вспомогательным атрибутов не использует инлайновые стили как CKEditor.

Когда вы редактируете контент в CKEditor, тут будут инлайновые стили, которые имеют больший вес в приоритезации, чем авторские. Что нам делать? Использовать !important и контролировать необходимое поведение.

Вспомогательные классы

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

.btn{
    display: inline-block;
    background: #3590f1;
    padding: 0.7em 1.6em;
    border-radius: 2px;
    font-size: 1rem;
    font-weight: 700;
    color: #fff;
    text-transform: uppercase;
    text-decoration: none;

    &:hover,
    &:focus {
        background: #5adba0;
    }
}

.entry-content a {
    text-decoration: underline;
    color: #3590f1;
}

Хотя с нашим классом .btn всё ок, его специфичность низка, так что простое второе правило, которое идет дальше — перепишет его свойства, в данном случае это color и text-decoration. Вам нужно написать простой селектор, но проблема всё же останется.

Вы можете решить ее, использовав !important, как в этом примере:

See the Pen
CSS !important with Utility Classes by Adam Laki (@adamlaki)
on CodePen.

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

БЭМ метод

БЭМ это тот метод, который основывается низкой специфичности и иногда из-за этого может вызывать некоторые неприятности со стилями. Почти все селекторы имеют один класс. Я даже не знаю сколько раз мне надо было рефакторить код, созданный по этой технике. Конечно, у вас есть и свои решения описанных проблем, но в следующий раз может вы тоже будете использовать !important.

Понравилась статья? Поделить с друзьями:
  • Use config tab is locked cisco как исправить
  • Usdownloader плагин вернул ошибку gdl error
  • Usd error что это значит
  • Urlopen error errno 2 name or service not known
  • Urlopen error errno 111 connection refused