css!important_如何解決CSS特殊性問題以及何時使用!important關鍵字

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393210.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393210.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393210.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

php框架使用教程,php框架laravel excel包使用教程介紹

Laravel是一套簡潔、優雅的PHP Web開發框架(PHP Web Framework)。它可以讓你從面條一樣雜亂的代碼中解脫出來;它可以幫你構建一個完美的網絡APP了,下面我們來看看laravel excel包使用教程laravel中excel插件的安裝在composer中引入laravel excel的包&quo…

(私人收藏)python學習(游戲、爬蟲、排序、練習題、錯誤總結)

python學習(游戲、爬蟲、排序、練習題、錯誤總結) https://pan.baidu.com/s/1dPzSoZdULHElKvb57kuKSgl7bz python100經典練習題python-錯誤和異常小結python-大作業之五子棋游戲(附代碼)python-網絡爬蟲幾種排序方法python實現新手常見的python運行時錯誤…

leetcode1300. 轉變數組后最接近目標值的數組和

給你一個整數數組 arr 和一個目標值 target ,請你返回一個整數 value ,使得將數組中所有大于 value 的值變成 value 后,數組的和最接近 target (最接近表示兩者之差的絕對值最小)。 如果有多種使得和最接近 target 的…

MySQL性能指標及計算方法

MySQL性能指標及計算方法 絕大多數MySQL性能指標可以通過以下兩種方式獲取: (1)mysqladmin 使用mysqladmin extended-status命令獲得的MySQL的性能指標,默認為累計值。如果想了解當前狀態,需要進行差值計算&#xff1b…

php可變變量講解,PHP可變變量實例詳解

什么是可變變量?在PHP中有一個其他類型的變量,“可變變量”。可變變量是一種PHP獨特的變量,他允許動態改變一個變量的名稱。可變變量的工作原理這個特性的工作原理是用一個變量的值作為另一個變量的名稱。例如,我們可以設置$str的…

Nginx平滑升級到最新版本

(一)簡述: 早上收到nginx最新漏洞的通知,Nginx官方發布最新的安全公告,在Nginx范圍過濾器中發現了一個安全問題(CVE-2017-7529),通過精心構造的惡意請求可能會導致整數溢出并且不…

如何使用TypeScript從Microsoft Word生成GitHub markdown文件

by Manish Bansal通過Manish Bansal What? Why would one want to generate an MD file from a Microsoft word document? If that’s the first thought you had after reading this title, then let me give you a strong use case.什么? 為什么要從Microsoft …

Android Studio 導入 Android 系統模塊并編譯和調試

FAQ: AS導入系統模塊源碼,并且能夠編譯調試,正常查看java doc ???? Android AOSP基礎(五)Android Studio調試系統源碼的三種方式http://liuwangshu.cn/framework/aosp/5-debug-aosp.html Android AOSP基礎(四&…

2014年ENVI/IDL遙感應用與開發培訓班-11月重慶站 開始報名了

主辦單位: 中國遙感應用協會 Esri中國信息技術有限公司 內容簡單介紹: 依據中國遙感應用協會欒恩杰理事長推動國內遙感技術和應用的指示精神,2014年中國遙感應用協會組織培訓交流部與Esri中國信息技術有限公司將共同在多個城市舉辦以"傳…

Python自動化運維:Django之View視圖和Template

views詳解 http請求中產生兩個核心對象: http請求:HttpRequest對象 http響應:HttpResponse對象 (1) HttpRequest對象 當請求一個頁面時,Django 創建一個 HttpRequest對象包含原數據的請求。然后 Django 加載…

leetcode491. 遞增子序列(回溯算法)

給定一個整型數組, 你的任務是找到所有該數組的遞增子序列&#xff0c;遞增子序列的長度至少是2。 示例: 輸入: [4, 6, 7, 7] 輸出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]] 代碼 class Solution {List<List<Integer>>…

java重入鎖,再探JAVA重入鎖

之前的文章中簡單的為大家介紹了重入鎖JAVA并發之多線程基礎(2)。這里面也是簡單的為大家介紹了重入鎖的幾種性質&#xff0c;這里我們就去探索下里面是如何實現的。我們知道在使用的時候&#xff0c;必須鎖先有定義&#xff0c;然后我們再拿著當前的鎖進行加鎖操作&#xff0c…

azure服務器_如何使用Azure Functions和SendGrid構建無服務器報表服務器

azure服務器It’s 2018 and I just wrote a title that contains the words “Serverless server”. Life has no meaning.那是2018年&#xff0c;我剛剛寫了一個標題&#xff0c;其中包含“無服務器服務器”一詞。 生活沒有意義。 Despite that utterly contradictory headli…

【GoWeb開發實戰】Cookie

cookie Web開發中一個很重要的議題就是如何做好用戶的整個瀏覽過程的控制&#xff0c;因為HTTP協議是無狀態的&#xff0c;所以用戶的每一次請求都是無狀態的&#xff0c;我們不知道在整個Web操作過程中哪些連接與該用戶有關&#xff0c;我們應該如何來解決這個問題呢&#xff…

PhotoKit 照片庫的管理-獲取圖像

PHAsset部分屬性解析 1、HDR 和全景照片 mediaSubtypes 屬性驗證資源庫中的圖像在捕捉時是否開啟了 HDR&#xff0c;拍攝時是否使用了相機應用的全景模式。 2、收藏和隱藏資源 要驗證一個資源是否被用戶標記為收藏或被隱藏&#xff0c;只要檢查 PHAsset 實例的 favorite 和 hid…

cmail服務器安裝后無法登錄的解決辦法

安裝cmailserver 5.4.6軟件安裝、注冊都非常順利&#xff0c;webmail頁面也都正常打開&#xff0c;但是一點“登錄”就提示錯誤&#xff1a; Microsoft VBScript 運行時錯誤 錯誤 800a01ad ActiveX 部件不能創建對象: CMailCOM.POP3.1 /mail/login.asp&#xff0c;行 42 點“…

matlab對人工智能,MATLAB與人工智能深度學習和機器學習.PDF

MATLAB與人工智能深度學習和機器學習MATLAB 與人工智能&#xff1a;深度學習有多遠&#xff1f;© 2017 The MathWorks, Inc.1機器學習8機器學習無處不在? 圖像識別 [TBD]? 語音識別? 股票預測? 醫療診斷? 數據分析? 機器人? 更多……9什么是機器學習&#xff1f;機…

leetcode1471. 數組中的 k 個最強值(排序)

給你一個整數數組 arr 和一個整數 k 。 設 m 為數組的中位數&#xff0c;只要滿足下述兩個前提之一&#xff0c;就可以判定 arr[i] 的值比 arr[j] 的值更強&#xff1a; |arr[i] - m| > |arr[j] - m| |arr[i] - m| |arr[j] - m|&#xff0c;且 arr[i] > arr[j] 請返回…

Spring中WebApplicationInitializer的理解

現在JavaConfig配置方式在逐步取代xml配置方式。而WebApplicationInitializer可以看做是Web.xml的替代&#xff0c;它是一個接口。通過實現WebApplicationInitializer&#xff0c;在其中可以添加servlet&#xff0c;listener等&#xff0c;在加載Web項目的時候會加載這個接口實…

使用fetch封裝請求_關于如何使用Fetch API執行HTTP請求的實用ES6指南

使用fetch封裝請求In this guide, I’ll show you how to use the Fetch API (ES6) to perform HTTP requests to an REST API with some practical examples you’ll most likely encounter.在本指南中&#xff0c;我將向您展示如何使用Fetch API(ES6 )來執行對REST API的 HTT…