2017-09-04 16 views
1

我有以下的HTML代碼:CSS屬性的身體需要的項重要關鍵字發生

<!DOCTYPE html> 
<html> 
<head> 
    <title>Project Web</title> 
</head> 

<body> 
    <h1>Hello, World!</h1> 
</body> 

<link href="index_style.css" rel="stylesheet"> 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 
</html> 

下面CSS(在index_style.css文件):

body { 
    background-color: black !important; 
    color: white !important; 
} 

正如你可以說,只有在後面跟着!important關鍵字時,「背景顏色」和「顏色」屬性纔會發生。這是爲什麼發生?

回答

5

您必須包含您的index_style.css鏈接您的引導代碼。

這是因爲您的樣式被任何引導樣式修改。

您希望通過首先包括bootstrap來設置默認值,而不是使用您自己的代碼更新這些屬性。

這被稱爲CSS中的優先級,一旦你理解它的工作原理,它就非常有用。

Precedence in CSS

我可以看到你的腳本命令另外一個問題,你的正確的順序應該是:

<!-- put these inside a <head></head> --> 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> 
<link href="index_style.css" rel="stylesheet"> 

<!-- put this just before closing </body> tag --> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 
+0

由於樣式是級聯的,所以瀏覽器採用更詳細或最後一種Style規則並應用它。因此,如果您在引導後包含css,則您的樣式是瀏覽器找到的最後一個樣式,因此它們將覆蓋引導規則。 –

2

發生這種情況是因爲你加載bootsrap的CSS 自己的CSS。當你這樣做的時候,Bootstrap的CSS將覆蓋你所有的body刪除,只有!important會導致它們被應用於引導程序的刪除。

要解決這個問題,在這個順序加載CSS文件:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> 
<link href="index_style.css" rel="stylesheet"> 
0

調用CSS文件的正確順序是問題在這裏,請使用您的自定義樣式後,引導風格,以解決這一問題,並會覆蓋其他樣式組件也是如此,所以正確的順序如下:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> 
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> 
<link href="index_style.css" rel="stylesheet"> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 
0

正如其他人所說,你的CSS正在被覆蓋。在包含外部CSS文件時,在外部文件之後添加您自己的CSS文件。

覆蓋規則也適用於CSS文件內部。

body { 
    background-color: black; 
    color: white !important; 
    background-color: red; 
} 

以下的背景顏色會變成紅色,因爲最後聲明瞭背景顏色。

無論最後聲明什麼都會覆蓋之前聲明的內容。請牢記這一點,因爲這將節省您未來的時間,並使其使用!重要的不必要的