css 选择器


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的名称区分大小写




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值