css 选择器

来源:互联网 发布:linux查看snmp版本 编辑:程序博客网 时间:2024/05/17 08:10


1 后代选择器(中间没有“.”中间没有"#")

<html><head><style type="text/css">h1 em {color:red;}</style></head><body><h1>This is a <em>important</em> heading</h1><p>This is a <em>important</em> paragraph.</p></body></html>

因为 em已经指定为h1的后代,所以只有作为h1的后代的标签才可以使用


具体应用

假设有一个文档,其中有一个边栏,还有一个主区。边栏的背景为蓝色,主区的背景为白色,这两个区都包含链接列表。不能把所有链接都设置为蓝色,因为这样一来边栏中的蓝色链接都无法看到。

解决方法是使用后代选择器。在这种情况下,可以为包含边栏的 div 指定值为 sidebar 的 class 属性,并把主区的 class 属性值设置为 maincontent。

div.sidebar {background:blue;}div.maincontent {background:white;}div.sidebar a:link {color:white;}div.maincontent a:link {color:blue;}


有关后代选择器有一个易被忽视的方面,即两个元素之间的层次间隔可以是无限的。

<ul>  <li>List item 1    <ol>      <li>List item 1-1</li>      <li>List item 1-2</li>      <li>List item 1-3        <ol>          <li>List item 1-3-1</li>          <li>List item <em>1-3-2</em></li>          <li>List item 1-3-3</li>        </ol>      </li>      <li>List item 1-4</li>    </ol>  </li>  <li>List item 2</li>  <li>List item 3</li></ul>

2 子元素选择器(“>”)

<!DOCTYPE HTML><html><head><style type="text/css">h1 > strong {color:red;}</style></head><body><h1>This is <strong>very</strong> important.</h1><h1>This is <em>really <strong>very</strong></em> important.</h1></body></html>

3 相邻元素选择器(“+”)

<!DOCTYPE HTML><html><head><style type="text/css">h1 + p {margin-top:50px;}</style></head><body><h1>This is a heading.</h1><p>This is paragraph.</p><p>This is paragraph.</p><p>This is paragraph.</p><p>This is paragraph.</p><p>This is paragraph.</p></body></html>

4 类选择器(“.”)

<html><head><style type="text/css">.important {color:red;}</style></head><body><h1 class="important">This heading is very important.</h1><p class="important">This paragraph is very important.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>...</p></body></html>


<html><head><style type="text/css">p.important {color:red;}h1.important {color:blue;}</style></head><body><h1 class="important">This heading is very important.</h1><p class="important">This paragraph is very important.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>...</p></body></html>

5 id选择器("#",同时使用id而不是class)

<html><head><style type="text/css">#intro {font-weight:bold;}</style></head><body><p id="intro">This is a paragraph of introduction.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>This is a paragraph.</p><p>...</p></body></html>

id在一个html当中只能使用一次

id的名称区分大小写




原创粉丝点击