Inline Styles
盡管CSS是不同于HTML的語言,但使用inline styles也可以在HTML code寫入CSS code蜓萄。
為給HTML element添加樣式,你可以直接在opening tag內(nèi)添加style屬性澄峰,然后你可以設置它等于你想要應用的CSS style(s) 嫉沽。
Inline styles are a quick way of directly styling an HTML element.
The <style> Tag
Inline styles 是一個快速為HTML加樣式的方法,但也有其局限性俏竞。如果你需要為multiple?<h1>?elements加樣式绸硕,你必須手動地(manually)為?each element??add inline styling 堂竟。
幸運的是,通過使用?<style>?element玻佩,HTML允許你在其內(nèi)部寫入CSS code出嘹,?CSS can be written between opening and closing?<style>?tags。但是使用時咬崔,?<style>?element 必須放置在?<head>?element 內(nèi)部税稼。
The .css file
開發(fā)者為避免mixing code,故將HTML and CSS code 存放在不同的文件內(nèi)垮斯。
通過使用.css后綴郎仆,你可以創(chuàng)建一個CSS文件,如:style.css
?Linking the CSS File
你可以使用<link>?element來鏈接HTML and CSS files兜蠕。它必須被放在the head of the HTML file 內(nèi)扰肌。它是自閉和標簽,且有以下三個屬性:
href?— like the anchor element, the value of this attribute must be the address, or path, to the CSS file.
type?— this attribute describes the type of document that you are linking to (in this case, a CSS file). The value of this attribute should be set to?text/css.
rel?— this attribute describes the relationship between the HTML file and the CSS file. Because you are linking to a stylesheet, the value should be set to?stylesheet.
當鏈接好了之后熊杨,<link>?element 應如下圖:
Tag Name
CSS can select HTML elements by using an element’s tag name. A tag name is the word (or character) between HTML angle brackets.
For example, in HTML, the tag for a paragraph element is?<p>. The CSS syntax for selecting?<p>?elements is:
In the example above, all paragraph elements will be selected using a CSS?selector.?
Class Name
To select this element using CSS, we could use the following CSS selector:
To select an HTML element by its class using CSS, a period (.) must be prepended to the class’s name.
Multiple Classes
ID Name
如果an HTML element需要被單獨賦予樣式曙旭,可以為其添加ID屬性。
要在CSS選擇它猴凹,則需在ID名前加#夷狰。
Specificity 明確性
Specificity 是指瀏覽器要應用哪一個CSS樣式。ID優(yōu)先級最高郊霎,其次clss沼头,最后是tag。
上圖中h1顏色應為firebrick书劝,因為?the class selector is more specific than the tag selector进倍。?
為使樣式易于編輯,最好的方式是:優(yōu)先使用a?tag selector购对,若不行猾昆,添加a class selector,若還不夠明確骡苞,再添加an ID selector垂蜗。
Chaining Selectors
If there was a?.special class for?h1 elements, the CSS would look like:
The code above would select only the?h1 elements that have a class of?special.
Nested Elements
CSS 也可以選擇那些嵌套在?other HTML elements 內(nèi)的elements。
若要選中嵌套在內(nèi)部的<li>:
在CSS選擇器前加一個?tag, class, or ID 會增加其specificity解幽。
Important
!important 可被應用于屬性中贴见,帶有 !important 的屬性將覆蓋(override)所有其他樣式,無論其優(yōu)先級多高躲株。故其很少被使用片部,因為它很難被覆蓋。
CSS中!important的語法結(jié)構(gòu)如下:
因為?!important 被用于p選擇器的顏色屬性中霜定,故所有的p elements 都將邊blue档悠,即使下方還有一個相對于p選擇器更明確的.main p selector廊鸥。
Multiple Selectors
為使CSS更加concise(簡潔),可以使multiple selectors辖所,它防止了重復的代碼出現(xiàn)惰说。
舉例來說,下圖代碼有重復啰嗦(repetitive)的屬性:
為不使font-family: Georgia在兩個選擇器中重復兩次奴烙,我們可以通過逗號(comma)將兩個選擇器隔開助被,再應用其共同的樣式:
By separating the CSS selectors with a comma, both the?h1?and the?.menu?elements will receive the?font-family: Georgia?styling.