代码改变世界

CSS 关于选择器

2016-08-22 16:50  yojiaku  阅读(154)  评论(0编辑  收藏  举报

Chapter 01 Basical Knowledges
· We should use meaningful elements, (X)HTML includes many meaningful elements, such as:
h1/h2...
ul, ol, dl
strong, em
blockquote, cite
abbr, acronym, code
fieldset, legend, label
caption, thead, tbody, tfoot
...

· However, list of available elements is not comprehensive, a simple way is to give element ID or
Class. The difference is that ID can only use once, Class can be used more than once.

· Most people think <div> doesn't have a semantic meaning, in fact, <div> means "division", it
provides a way to divide a document into a meaningful area.
(其实div是division的缩写,它提供了将文档分割为有意义区域的方法。)

·Selector
1.Type Selectors (类型选择器)
p{color: black;}
a{text-decoration: underline}
h1{font-weight: bold;}
...
2.Descendent Selectors (后代选择器)
li a{text-decoration: none;}
...
3.ID Selectors & Class Selectors (ID选择器和类选择器)
#intro{font-weight: bold;}
.datePosted{color: green;}

<p id="intro">Some Text</p>
<p class = "datePodted">22/8/2016</p>
...
4.Pseudo Class (伪类)
/* makes all univisited links blue */
a:link {color: blue;}

/* makes all visited links green */
a:visited {color: green;}

/* makes links red when hovered or activated */
a:hover, a:active {color: red;}

/* makes input elements yellow when focus is applied */
input:focus {background-color: yellow;,}

:link & :visited are called "Link Pseudo Class", only can be applied to anchor elements (锚元素);
:hover, :active & :focus are called "Dynamic Pseudo Class", can be applied to all elements.

5.General Selectors (通用选择器)
*{
padding: 0;
margin: 0;
}

6.Child Selectors (子选择器)
#nav > li {
background:url(folder.png) no-repeat left top;
}

<ul id="nav">
<li>Home</li>
<li>Services
<ul>
<li>Design</li>
<li>Development</li>
<li>Consultancy</li>
</ul>
</li>
<li>Contact Us</li>
</ul>
(在上面的示例中,外层列表中的列表项显示一个定制的图标,而嵌套列表中的列表项不受影响)

7.Adjacent Sibling Selectors (相邻同胞选择器)
h1 + p{
font-weight: bold;
}

<h1>Main Heading</h1>
<p>First Paragraph</p>
<p>Second Paragraph</p>
(只是将第一个p标签的内容粗体显示,后面的段落不受影响)

8.Attribute Selectors (属性选择器)
eg1:
abbr[title] {border-bottom: 1px dotted #999;}
abbr[title]:hover {cursor: help;}

eg2:
a[rel="nofollow"] {
background-image: url(nofollow.png);
padding-right: 20px;
}

eg3:
a[rel~="friend"] {
background-image: url(friend.gif);
}

<a href="http://www.xxx.com/" rel="friend met colleague"> John Hicks </a>