要用CSS樣式化一個HTML元素,必需要定位一個元素, CSS的選擇器就是這樣的手段。css
這章中,你要學到的瀏覽器
• Common selectors 普通選擇器
• Advanced selectors 高級選擇器
• New CSS 3 selectors 新的CSS3選擇器
• The wonderful world of specificity and the cascade 特徵和層疊的奇妙世界
• Planning and maintaining your style sheets 規劃維護樣式表
• How to comment your code 註釋代碼app
最經常使用的選擇器是 類型選擇器 type selector和 後代選擇器 descendant selector。類型選擇器用來選擇某種類型元素. ide
好比Paragraph, h1,只須要指定但願樣式化的元素佈局
p {color: black;}
h1 {font-weight: bold;}post後代選擇器容許選擇 某個特定的或一組元素的子元素,後代選擇器使用兩個選擇器組合中間空格隔開。性能
blockquote p {padding-left: 2em;}測試
只有Blockquote跟着paragraph 纔會被選中, 樣式是縮進2em。 其餘的paragraph不受影響。字體
另兩種常見的選擇器是ID和class選擇器, ID選擇器用Hash Character來表示 #, class選擇器用Period來表示 .舉例:優化
#intro {font-weight: bold;}
.date-posted {color: #ccc;}
<p id="intro">Happy Birthday Andy</p>
<p class="date-posted">24/3/2009</p>以前說過,開發者過度依賴 class and ID 選擇器. 若是想用某種方式樣式化Main Content下面的H2, 又想用另外一種方式樣式化Secondary Content下面的H2, 一種傾向是兩種樣式各用一個Class名, 一個更簡單的方式多是用 類型, ID, class 和後代選擇器的組合方式。
If they want to style headlines one way in the main content area and another way in the
secondary content area, there is the tendency to create two classes and apply a class to each
headline. A much simpler approach is to use a combination of type, descendant, ID, and/or class
selectors:#main-content h2 {font-size: 1.8em;}
#secondaryContent h2 {font-size: 1.2em;}
<div id="main-content">
<h2>Articles</h2>
...
</div>
<div id="secondary-content">
<h2>Latest news</h2>
...
</div>以上四種選擇器差很少已經能夠應付大多狀況。
僞類
有時候你可能不是根據文檔結構來選擇元素, 例如表單元素和連接的狀態, 這能夠用僞類選擇器來解決。
/* makes all unvisited links blue */
a:link {color:blue;}/* makes all visited links green */
a:visited {color:green;}/* makes links red when hovered or activated.
focus is added for keyboard support */
a:hover, a:focus, a:active {color:red;}/* makes table rows red when hovered over */
tr:hover {background-color: red;}/* makes input elements yellow when focus is applied */
input:focus {background-color:yellow;}:link and :visited are known as link pseudo-classes and can only be applied to anchor
elements. :hover, :active, and :focus are known as dynamic pseudo-classes and can
theoretically be applied to any element. Most modern browsers support this functionality.僞類能夠被串接起來,造成更復雜的行爲
/* makes all visited linkes olive on hover */
a:visited:hover {color:olive;}
全局選擇器
最強大和最少用的是全局選擇器,像一個通配符,匹配任何元素,用一個星號標識,
For instance, you can remove the default browser
padding and margin on every element using the following rule:* {
padding: 0;
margin: 0;
}
When combined with other selectors, the universal selector can be used to style all the
descendants of a particular element or skip a level of descendants. You will see how this can be
put to practical effect a little later in this chapter.
CSS2.1和CSS3有其餘一些有用的選擇器,不幸的是大部分現代瀏覽器都支持,可是IE6等老一代瀏覽器不支持, 幸運的是CSS回溯匹配,若是瀏覽器不理解,它忽略整個規則,你能夠不用擔憂老一點的瀏覽器會出問題, 只要記住不要在關鍵的功能和佈局使用這些選擇器就好。
子選擇器和相鄰同胞選擇器
第一個複雜選擇器是子選擇器,不一樣於後代選擇器選擇全部的後代, 子選擇器只選擇緊跟的後代,或兒子, 舉例:
#nav>li {
background: url(folder.png) no-repeat left top;
padding-left: 20px;
}
<ul id="nav">
<li><a href="/home/">Home</a></li>
<li><a href="/services/">Services</a>
<ul>
<li><a href="/services/design/">Design</a></li>
<li><a href="/services/development/">Development</a></li>
<li><a href="/services/consultancy/">Consultancy</a></li>
</ul>
</li>
<li><a href="/contact/">Contact Us</a></li>
</ul>IE7可能有小Bug,若是父子元素間出現了Comments註釋?
It is possible to fake a child selector that works in IE 6 and below by using the universal selector.
To do this, you first apply to all of the descendants the style you want the children to have. You
then use the universal selector to override these styles on the children’s descendants. So to fake
the previous child selector example you would do this:#nav li {
background: url(folder.png) no-repeat left top;
badding-left: 20px;
}
#nav li * {
background-image: none;
padding-left: 0;
}有時候你可能會想根據相鄰的另外一個元素樣式化, 那麼相鄰同胞選擇器可讓你選擇排在前面的同在一個父元素下的元素。
h2 + p {
font-size: 1.4em;
font-weight: bold;
color: #777;
}
<h2>Peru Celebrates Guinea Pig festival</h2>
<p>The guinea pig festival in Peru is a one day event to celebrate
these cute local animals. The festival included a fashion show where
animals are dressed up in various amusing costumes.</p>
<p>Guinea pigs can be fried, roasted, or served in a casserole. Around
65 million guinea pigs are eaten in Peru each year.</p>
屬性選擇器
As the name suggests, the attribute selector allows you to target an element based on the
existence of an attribute or the attribute’s value. This allows you to do some very interesting and
powerful things.就像名字表示的那樣,屬性選擇器根據屬性的存在與否或屬性值來命中目標, 這樣能夠作一些強大有趣的事情。
For example, when you hover over an element with a title attribute, most browsers will display a
tooltip. You can use this behavior to expand the meaning of things such as acronyms and
abbreviations:
<p>The term <acronym title="self-contained underwater breathing
apparatus">SCUBA</acronym> is an acronym rather than an abbreviation
as it is pronounced as a word.</p>
However, there is no way to tell that this extra information exists without hovering over the
element. To get around this problem, you can use the attribute selector to style acronym elements
with titles differently from other elements—in this case, by giving them a dotted bottom border.
You can provide more contextual information by changing the cursor from a pointer to a question
mark when the cursor hovers over the element, indicating that this element is different from most.
acronym[title] {
border-bottom: 1px dotted #999;
}
acronym[title]:hover, acronym[title]:focus {
cursor: help;
}
In addition to styling an element based on the existence of an attribute, you can apply styles
based on a particular value. For instance, sites that are linked to using a rel attribute of nofollow
gain no added ranking benefit from Google. The following rule displays an image next to such
links, possibly as a way of showing disapproval of the target site:
a[rel="nofollow"] {
background: url(nofollow.gif) no-repeat right center;
padding-right: 20px;
}
層疊和特殊性
更復雜的CSS樣式表,有可能兩個或多個規則命中同一個元素, CSS經過用層疊的過程來解決衝突,層疊給每一個規則分配一個重要度, 做者編輯的樣式表被認爲最重要,其次是用戶樣式表,最後是瀏覽器和用戶代理樣式,爲了給用戶有更多控制,能夠將任何規則制定爲!important 來提升他的重要度,讓它優先於任何規則, 下面是重要度排列規則
• User styles flagged as !important
• Author styles flagged as !important
• Author styles
• User styles
• Styles applied by the browser/user agent根據選擇器的特殊性決定規則的次序, 更特殊選擇器的規則優先於比較通常的選擇器規則, 若是兩個規則特殊性相同,那麼後定義的規則優先。
特殊性(specificity)
這裏看書不解釋
在樣式表使用特殊性
特殊性在寫CSS樣式表的時候頗有用, 它容許你爲通常元素設定通常樣式規則, 而後再特殊元素再去覆蓋它,好比你要在全站使用黑色字,在Intro字體使用灰色,你能夠這樣作:
p {color: black;}
p.intro {color: grey;}
在body標籤添加一個ID或一個Class
給Body標籤添加一個ID和Class是使用特殊性的一個有趣方法,Class用來覆蓋整站的樣式, 好比全部News頁面都有特別的樣式。
body.news {
/* do some stuff */
}
<body class="news">
<p>My, what a lovely body you have.</p>
</body>有時候你須要在某特定頁面覆蓋這些樣式, 好比Archive的News頁面, 這種狀況,添加ID到那個特定頁面的Body標籤就行了。
body.news {
/* do some stuff */
}
body#archive {
/* do some different stuff */
}
<body id="archive" class="news">
<p>My, what a lovely body you have.</p>
</body>這樣頁面的可維護性大大提升。
繼承
繼承和層疊看似類似,但其實很不一樣,繼承其實很容易理解, 有些屬性,好比color 或 font size, 被元素的後代繼承,因而就做用到它們之上。
應用樣式到你的文檔
能夠在文檔頂部的Style標籤內添加樣式, 這個不是個明智的方法, 若是要在另個頁面應用一樣的樣式,就不得不復制到另外一也頁面上,若是要修改樣式,就要在兩個地方修改。 幸運的是,CSS容許把全部的樣式都放到一個或幾個外部樣式表中, 有兩種方法把外部樣式表附加到文檔中。 連接link 或 導入import
<link href="/css/basic.css" rel="stylesheet" type="text/css" />
<style type="text/css">最近的測試代表導入import可能帶來性能問題。 因此下面僅做知識補充,不建議採用
<!--
@import url("/css/advanced.css");
-->
</style>能夠將一個樣式表導入import到另外一個樣式表中,而不限於只導入到HTML文檔中, 例如
@import url(/css/layout.css);
@import url(/css/typography.css);
@import url(/css/color.css);However, recent browser benchmarking has shown that importing style sheets can be slower than linking to them.
爲了維護性,最好能註釋你的代碼,便於維護和移交。 用 /* bla bla bla */ 來註釋,能夠多行。例如:
/* Body Styles */
body {
font-size: 67.5%; /* Set the font size */
}也能夠在註釋中添加特殊標記的形式,便於查找 好比@group
/* @group typography */
結構化代碼
把樣式表分割成合理的區塊便於維護, 咱們常以通常的樣式開頭, 包括Body標籤的樣式, 應該被整站繼承的樣式, 其次是全局重置的樣式,
跟着是link, heading, 和其餘元素。
一旦通常的樣式都有了,就能夠開始更特殊的 和幫助性的樣式, 這些是通常性的跨站使用的,包括 form, 錯誤信息, 而後就是 結構元素像
佈局 layout和 導航 navigation。
當往下走, 咱們慢慢從頭開始添加樣式, 愈來愈特殊, 而後頁面的裝備就差很少齊備而後轉移注意力到頁面相關的元素。 最後是任何藥覆蓋和例外的底部元素, 文檔結構像下面這樣:
• General styles
• Body styles
• Resets
• Links
• Headings
• Other elements
• Helper styles
• Forms
• Notifications and errors
• Consistent items
• Page structure
• Headers, footers, and navigation
• Layout
• Other page furniture
• Page components
• Individual pages
• Overrides
給本身用的筆記
顏色值列表
/* Color Variables
@colordef #434343; dark gray
@colordef #f2f6e4; light green
@colordef #90b11f; dark green
@colordef #369; dark blue
*/
To make your comments more meaningful, you can use keywords to distinguish important
comments. I use @todo as a reminder that something needs to be changed, fixed, or revisited
later on, @bugfix to document a problem with the code or a particular browser, and @workaround
to explain a nasty workaround:
/* :@todo Remember to remove this rule before the site goes live */
/* @workaround: I managed to fix this problem in IE by setting a small
negative margin but it's not pretty */
/* @bugfix: Rule breaks in IE 5.2 Mac */www.cssoptimiser.com 這個網站能夠壓縮優化CSS樣式表