本文主要是介绍css派生选择器、id选择器、类选择器、属性选择器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.派生选择器
也叫上下文选择器,可以根据上下文关系来定义样式。无需为特别为元素设置id 或者class,使代码更简单。
例如.希望列表中的,<strong>变成斜体。
li strong {
font-style: italic;
font-weight: normal;
}
施加影响的html.
<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>
<ol>
<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>
strong {
color: red;
}
h2 {
color: red;
}
h2 strong {
color: blue;
}
施加影响的html:
<p>The strongly emphasized word in this paragraph is<strong>red</strong>.</p>
<h2>This subhead is also red.</h2>
<h2>The strongly emphasized word in this subhead is<strong>blue</strong>.</h2>
2.css id 选择器
id 选择器以#来定义。每个id 属性只能在每个 HTML 文档中出现一次。即一个id只能给一个标签唯一使用,不能赋值给多个标签。
id 选择器经常与派生选择器连用。
例.
#red {color:red;}
#green {color:green;}
施加影响的html:
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
例.#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}
注释:id是sidebar的标签内的 段落 会被设置此样式。也就是说p标签只是其中一个。如果div有 sidebar这个id,那么其中的p标签会被设置成上述样式。
3.类选择器
类选择器以 . 号定义。
class也可以作为派生选择器。.fancy td
元素也可以基于它们的类二被选择。td.fancytd.
.center {text-align: center}
施加影响的html:
<h1 class="center">
This heading will be center-aligned
</h1>
<p class="center">
This paragraph will also be center-aligned.
</p>
例.
.fancy td {
color: #f60;
background: #666;
}
注释:类名为 fancy 的更大的元素内部的表格单元都会以灰色背景显示橙色文字.
例.
td.fancy {
color: #f60;
background: #666;
}
{
color:red;
}
{
border:5px solid blue;
}
例1.属性和值选择器:多个值。适用于由空格分隔的属性值:[title~=hello] { color:red; }
[attribute] 用于选取带有指定属性的元素。
[attribute=value] 用于选取带有指定属性和值的元素。
[attribute~=value] 用于选取属性值中包含指定词汇的元素。
[attribute|=value] 用于选取带有以指定值开头的属性值的元素,该值必须是整个单词。
[attribute^=value] 匹配属性值以指定值开头的每个元素。
[attribute$=value] 匹配属性值以指定值结尾的每个元素。
[attribute*=value] 匹配属性值中包含指定值的每个元素。
<html>
<head>
<style type="text/css">
[title~=hello]
{
color:red;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<h2 title="hello world">Hello world</h2>
<p title="student hello">Hello W3School students!</h1>
<hr />
</body>
</html>
<html>
<head>
<style type="text/css">
[lang|=en]
{
color:red;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<p lang="en">Hello!</p>
<p lang="en-us">Hi!</p>
<hr />
<h1>无法应用样式:</h1>
<p lang="us">Hi!</p>
<p lang="zh">Hao!</p>
</body>
</html>
{
width:150px;
display:block;
margin-bottom:10px;
background-color:yellow;
font-family: Verdana, Arial;
}
input[type="button"]
{
width:120px;
margin-left:35px;
display:block;
font-family: Verdana, Arial;
}
5.创建css
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
<style type="text/css">
hr {color: sienna;}
p {margin-left: 20px;}
body {background-image: url("images/back40.gif");}
</style>
</head>
This is a paragraph
</p>
color: red;
text-align: left;
font-size: 8pt;
}
而内部样式表拥有针对 h3 选择器的两个属性:
h3 {
text-align: right;
font-size: 20pt;
}
假如拥有内部样式表的这个页面同时与外部样式表链接,那么 h3 得到的样式是:
color: red;
text-align: right;
font-size: 20pt;
这篇关于css派生选择器、id选择器、类选择器、属性选择器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!