css!important
by Muna Mohamed
通過穆納·穆罕默德(Muna Mohamed)
如何解決CSS特殊性問題以及何時使用!important關鍵字 (How to tackle CSS specificity issues and when to use the !important keyword)
案例研究 (A Case Study)
Recently, there was a Twitter poll floating around where the user asked their followers a question about CSS specificity . Unfortunately, I was unable to find the original tweet (comment below if you happen to find it!) but long story short, the majority of people got the answer wrong.
最近,有一個Twitter民意調查在用戶附近向用戶詢問有關CSS特殊性的問題。 不幸的是,我無法找到原始推文(如果發現它,請在下面評論!),但長話短說,大多數人都給出了錯誤的答案。
That Twitter poll (and its aftermath) led to me brushing up on my own knowledge of the topic of specificity and in turn, made me start fixing specificity issues in my own projects — which brings me to the purpose of this post.
Twitter的民意測驗(及其后果)使我重新審視了自己對特異性主題的認識,從而使我開始在自己的項目中解決特異性問題,這使我明白了這篇文章的目的。
In this post, we will be refactoring CSS code from a project of mine that has CSS specificity issues that are in need of fixing.
在這篇文章中,我們將從一個我的項目中重構CSS代碼,該項目存在需要修復CSS特殊性問題。
CSS特異性 (CSS Specificity)
定義 (Definition)
Specificity is described by MDN Web Docs as:
MDN Web文檔將特異性描述為:
the means by which browsers decide which CSS property values are the most relevant to an element and therefore, applied.
瀏覽器確定哪些CSS屬性值與元素最相關并因此被應用的方法。
規則 (Rules)
When deciding which CSS property values are the most relevant to apply to an element, the browser uses the source order (i.e the cascade) of the CSS stylesheet to determine this. But this rule applies when the CSS selectors have equal specificity. What happens when the specificity of one CSS selector is higher than another?
在確定哪些CSS屬性值與元素最相關時,瀏覽器使用CSS樣式表的源順序(即級聯)來確定。 但是,當CSS選擇器具有相同的特異性時,該規則適用。 當一個CSS選擇器的特異性高于另一個時,會發生什么?
In that case, browsers will use the specificity of a CSS selector to determine what CSS statements to apply. The higher the specificity of a CSS selector, the more likely that browsers will apply its CSS declarations over another.
在這種情況下,瀏覽器將使用CSS選擇器的特殊性來確定要應用CSS語句。 CSS選擇器的特異性越高,瀏覽器就越有可能將其CSS聲明應用于另一個。
nav a {color: green;
}a {color: red;
}
For example, in the example above, both of the CSS selectors are targeting the same HTML element, the anchor tag. In order to determine which CSS rule to apply to the anchor tag, the browser will calculate the specificity value and check which one is the highest. In this case, the first selector has a higher specificity value, therefore the browser will use its declarations to apply to the anchor tag.
例如,在上面的示例中,兩個CSS選擇器都針對同一HTML元素(錨標記)。 為了確定要應用于錨標記CSS規則,瀏覽器將計算出特異性值并檢查哪一個是最高的。 在這種情況下,第一個選擇器具有更高的特異性值,因此瀏覽器將使用其聲明將其應用于錨標記。
I’d like to point out here that although !important is not a CSS selector, it is a keyword that is used to forcefully override a CSS rule regardless of the specificity value, origin or source order of a CSS selector. Some use cases include:
我想在這里指出,盡管!important不是CSS選擇器,但它是一個關鍵字,用于強制覆蓋CSS規則,而與CSS選擇器的特異性值,來源或源順序無關。 一些用例包括:
- Temporary fixes (a bit like putting duct-tape on a leaky pipe) 臨時修復(有點像將膠帶綁在泄漏的管道上)
- Overriding inline styling 覆蓋內聯樣式
- Testing/debugging purposes 測試/調試目的
As useful as using the !important keyword may seem, the use of it can be more problematic than helpful. Over time, it can make it difficult to maintain your CSS and it can negatively affect the readability of your stylesheet, particularly for anyone else who is or will be working with it in the future.
盡管使用!important關鍵字似乎很有用,但使用它可能會比沒有幫助更成問題。 隨著時間的流逝,它可能會使您CSS難以維護,并且可能會對樣式表的可讀性產生負面影響,尤其是對于將來將要使用或將要使用它的任何人。
Which brings us to what we’ll be doing today — fixing the specificity issues in a project.
這使我們進入了今天要做的事情-解決了項目中的特殊性問題。
該項目 (The Project)
A little background about the project we’ll be refactoring — it is a Netflix inspired landing page using MovieDB’s API.
關于我們將要重構的項目的一些背景知識-它是使用MovieDB API的,受Netflix啟發的登錄頁面。
樣式表 (The stylesheet)
The aim is to remove the “!important” keyword from the CSS rules that it has been applied to by refactoring the code so that it follows specificity rules.
目的是通過重構代碼以使其遵循特定性規則,從而從已應用CSS規則中刪除“!important”關鍵字。
Below, you can see the stylesheet for the project.
在下面,您可以看到該項目的樣式表。
@import url("https://fonts.googleapis.com/css?family=Montserrat:400,400i,700");body {margin: 0;padding: 0;overflow-x: hidden;
}.wrapper {width: 100%;
}.wrapper #header {position: fixed;z-index: 300;padding: 15px;width: calc(100% - 30px);display: flex;justify-content: space-between;align-items: center;background: linear-gradient(to bottom, black 0%, transparent 100%);
}.wrapper #header #brand-logo {color: #d32f2f;text-shadow: 1px 1px 2px black;letter-spacing: 5px;text-transform: uppercase;font-family: Montserrat;font-weight: bold;font-size: 22px;
}.wrapper #header #menu-icon {display: none;
}.wrapper #header .nav-link,
.wrapper #header .icon {color: #bdbdbd;cursor: pointer;
}.wrapper #header .nav-menu {width: 400px;display: flex;justify-content: space-around;align-items: center;
}.wrapper #header .nav-link {padding: 5px 10px;font-size: 15px;font-family: century gothic;text-decoration: none;transition: background-color 0.2s ease-in;
}.wrapper #header .nav-link:hover {color: #c62828;background-color: rgba(0, 0, 0, 0.7);
}.wrapper #header .icon {font-size: 16px;
}.wrapper #header .icon:hover {color: #c62828;
}.wrapper #site-banner,
.wrapper #categories {width: 100%;
}.wrapper #site-banner {height: 550px;background-image: url("https://s1.gifyu.com/images/rampage_2018-1024x576.jpg");background-size: cover;background-position: center;background-repeat: no-repeat;background-attachment: fixed;
}.wrapper #site-banner .main-movie-title,
.wrapper #site-banner .watch-btn,
.wrapper #site-banner .main-overview {position: absolute;z-index: 3;
}.wrapper #site-banner .main-movie-title, .wrapper #site-banner .watch-btn {text-transform: uppercase;
}.wrapper #site-banner .main-movie-title {top: 120px;left: 20px;background: -webkit-linear-gradient(#ff9100, #dd2c00);-webkit-background-clip: text;-webkit-text-fill-color: transparent;font-size: 55px;font-family: Montserrat;font-weight: bold;
}.wrapper #site-banner .main-overview {width: 400px;top: 230px;left: 25px;color: #fafafa;line-height: 25px;font-family: helvetica;
}.wrapper #site-banner .watch-btn {width: 150px;height: 35px;top: 350px;left: 25px;border: none;border-radius: 20px;color: #fafafa;cursor: pointer;transition: all 0.2s ease-in;background-color: #ff0000;box-shadow: 1px 5px 15px #940000;
}.wrapper #site-banner .watch-btn:hover {color: #F5F5F5;background-color: #940000;
}.wrapper .after {position: relative;top: 0;left: 0;z-index: 2;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.3);
}.wrapper #categories {padding: 30px 0;display: flex;flex-direction: column;background: linear-gradient(to top, #090909 0%, #000000 100%);overflow: hidden;
}.wrapper #categories .category {margin: 30px 0;
}.wrapper #categories .category-header, .wrapper #categories .content {margin-left: 20px;color: #B0BEC5;font-family: helvetica;
}.wrapper #categories .category-header {margin-bottom: 50px;font-weight: normal;letter-spacing: 5px;
}.wrapper #categories .content {position: relative;right: 0;display: flex;justify-content: flex-start;transition: all 3s ease-in-out;
}.wrapper #categories .movie {margin-right: 10px;display: flex;flex-direction: column;align-items: center;justify-content: flex-start;
}.wrapper #categories .movie-img {transition: all 0.2s ease-in;
}.wrapper #categories .movie-img:hover {-webkit-filter: contrast(1.1);filter: contrast(1.1);-webkit-transform: scale(1.05);transform: scale(1.05);cursor: pointer;
}.wrapper #footer {width: 100%;height: 120px;background-color: #090909;display: flex;align-items: flex-end;justify-content: flex-start;
}.wrapper #footer #copyright-label {margin-left: 20px;padding: 10px;color: rgba(255, 255, 255, 0.3);opacity: 0.7;letter-spacing: 2px;font-family: helvetica;font-size: 12px;
}//Media Query
@media (max-width: 750px) {.nav-menu {visibility: hidden;}#menu-icon {display: block !important;font-size: 22px;}.main-movie-title {font-size: 45px !important;}.main-overview {width: 350px !important;font-size: 14px !important;}.watch-btn {width: 130px !important;height: 25px !important;font-size: 13px;}.movie-img {width: 170px;}
}
So, we can see from the stylesheet that the use of the !important keyword is mainly focused in the media query section which outlines the styles that the browser should apply when the screen-width is less than 750 pixels.
因此,我們可以從樣式表中看到!important關鍵字的使用主要集中在媒體查詢部分,該部分概述了當屏幕寬度小于750像素時瀏覽器應采用的樣式。
So, what happens when we remove the !important keyword from the CSS rules that it has been applied to? Well, we no longer have a “trump card” forcefully overriding the CSS rules of other CSS selectors that target the same HTML element. So, the browser will look at the stylesheet to see if there are any conflicting CSS rules.
那么,當我們從CSS規則中刪除!important關鍵字時會發生什么呢? 好了,我們不再擁有“王牌”,可以強行覆蓋其他針對同一HTML元素CSS選擇器CSS規則。 因此,瀏覽器將查看樣式表以查看是否存在任何沖突CSS規則。
If there are, then in order to determine which CSS rules to apply over another, the browser will use the source order, specificity and importance of the CSS selectors. If the CSS selectors with conflicting CSS rules have equal specificity, then the browser will use the source order rule and apply the CSS rules of the CSS selector that comes lower down in the stylesheet. Using this information, we can see that this situation is not the case for our stylesheet.
如果存在,則為了確定要在另一個CSS規則上應用CSS規則,瀏覽器將使用CSS選擇器的源順序,特異性和重要性。 如果具有沖突CSS規則CSS選擇器具有相同的特異性,則瀏覽器將使用源順序規則,并應用樣式表中位于下方CSS選擇器CSS規則。 使用此信息,我們可以看到樣式表不是這種情況。
But, if the CSS selectors with conflicting CSS rules don’t have equal specificity, then the browser will apply the CSS rules of the CSS selector that has higher specificity. We can see from our stylesheet that this is the case; the CSS selectors in our media query have lower specificity than the CSS selectors in the main part of our stylesheet.
但是,如果CSS規則沖突CSS選擇器沒有相同的特異性,則瀏覽器將應用具有更高特異性CSS選擇器CSS規則。 從樣式表中可以看出是這種情況。 媒體查詢中CSS選擇器的特異性低于樣式表主要部分中CSS選擇器。
Now that we have identified the issue, let’s fix it!
現在我們已經確定了問題,讓我們解決它!
First we have to locate the corresponding CSS selectors that match the CSS selectors in our media query.
首先,我們必須在媒體查詢中找到與CSS選擇器匹配的相應CSS選擇器。
.wrapper #header #menu-icon {display: none;
}.wrapper #site-banner .main-movie-title {...font-size: 55px;...
}.wrapper #site-banner .main-overview {width: 400px;...
}.wrapper #site-banner .watch-btn {width: 150px;height: 35px;...
}@media (max-width: 750px) {
#menu-icon {display: block !important;...}.main-movie-title {font-size: 45px !important;}.main-overview {width: 350px !important;font-size: 14px !important;}.watch-btn {width: 130px !important;height: 25px !important;...}
}
We can see that the CSS selectors in the main part of the stylesheet have higher specificity than the corresponding CSS selectors in the media query. Despite the CSS selectors in the media query appearing later on in the stylesheet, because of specificity rules (which take precedence over source order rules), the browser will apply the CSS rules of the CSS selectors that come before it.
我們可以看到,樣式表主要部分中CSS選擇器比媒體查詢中相應CSS選擇器具有更高的特異性。 盡管媒體查詢中CSS選擇器出現在樣式表的后面,但由于特定性規則(優先于源順序規則),瀏覽器仍將應用其前面CSS選擇器CSS規則。
To fix this, we must increase the specificity values of the CSS selectors in the media query. If we make it so that the CSS selectors that target the same HTML elements have equal specificity, then the browser will follow the source order rule. The CSS rules outlined in the media query (that’s located lower down in the stylesheet) will be applied when the screen-width is less than 750 pixels.
要解決此問題,我們必須增加媒體查詢中CSS選擇器的特異性值。 如果我們做到了使針對相同HTML元素CSS選擇器具有相同的特異性,那么瀏覽器將遵循源順序規則。 當屏幕寬度小于750像素時,將應用媒體查詢中概述CSS規則(位于樣式表的下方)。
The end result will look like this:
最終結果將如下所示:
.wrapper #header #menu-icon {display: none;
}.wrapper #site-banner .main-movie-title {...font-size: 55px;...
}.wrapper #site-banner .main-overview {width: 400px;...
}.wrapper #site-banner .watch-btn {width: 150px;height: 35px;...
}@media (max-width: 750px) {
.wrapper #header #menu-icon {display: block;...}.wrapper #site-banner .main-movie-title {font-size: 45px;}.wrapper #site-banner .main-overview {width: 350px;font-size: 14px;}.wrapper #site-banner .watch-btn {width: 130px;height: 25px;font-size: 13px;}
}
And that’s it! We have removed all traces of the !important keyword from the stylesheet. Already we can see that the stylesheet is easier to read, and you can imagine that our refactored stylesheet would be a lot easier to work with and maintain (particularly if others will be working on it too).
就是這樣! 我們從樣式表中刪除了!important關鍵字的所有痕跡。 我們已經看到樣式表更易于閱讀,并且您可以想象我們重構后的樣式表將更易于使用和維護(尤其是如果其他人也將對其進行處理)。
結論 (Conclusion)
So, what have we learned?
所以我們學了什么?
We have learned about how browsers determine which CSS styles to apply by using the source order, specificity and origin of selectors. We have also learned about the problems which can arise by using !important in your CSS and why its use should be kept to a bare minimum.
我們已經了解了瀏覽器如何通過使用選擇器的源順序,特異性和來源來確定要應用CSS樣式。 我們還了解了在CSS中使用!important可能引起的問題,以及為什么應盡量減少使用它。
We do not have to resort to using !important in order to fix things — there are much better solutions out there.
我們不必依靠!important來解決問題-那里有更好的解決方案。
The concept of specificity is one that can take a while to get your head around, but I hope that by documenting the process and using a real project, it helps you better understand the concept of specificity and how to apply it in your own CSS.
特異性的概念可能需要一段時間才能引起您的注意,但是我希望通過記錄過程并使用一個真實的項目,它可以幫助您更好地理解特異性的概念以及如何將其應用于您自己CSS中。
Additional Resources
其他資源
MDN Web Docs
MDN網絡文檔
Batficity by Mandy Michael
Mandy Michael的 蝙蝠俠
CSS Specificity Wars by Andy Clarke
CSS特異性大戰 ( Andy Clarke)
Specificity Visualizer by Francesco Schwarz.
Francesco Schwarz的 特異性可視化儀 。
When using !important is the right choice by Chris Coyier
當使用!important是 Chris Coyier 的正確選擇
You can find the project we’ve been working on here.
您可以在這里找到我們一直在努力的項目。
希望您喜歡這篇文章! 如果您這樣做了,??,? 和分享! 直到下一次! ?? (I hope you enjoyed this post! If you did, ??, ? and share! Till next time! ??)
翻譯自: https://www.freecodecamp.org/news/how-to-tackle-css-specificity-issues-and-when-to-use-the-important-keyword-b54123995e1a/
css!important