您的位置:首页 > Web前端 > CSS

CSS语法结构和选择器

2016-07-17 00:18 453 查看
CSS语法组成部分:选择器、属性、值

selector { property : value }

selector 有:类选择器、id选择器、派生选择器

举例说明用法

类选择器

类选择器格式 .类名

html代码
<p class="center">
This paragraph will also be center-aligned.
</p>
css代码
.center {text-align: center}

类选择器的派生选择器
.fancy td {
color: #f60;
background: #666;
}
//类名为 fancy 的更大的元素内部的表格单元都会以灰色背景显示橙色文字。

td.fancy {
color: #f60;
background: #666;
}
//类名为 fancy 的表格单元将是带有灰色背景的橙色。


id选择器

id选择器可以为有特定id的html标签来指定样式,格式是” #id “。

id选择器也可以用来指定派生选择器

html代码
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
css代码
#red {color:red;}
#green {color:green;}

派生选择器的用法
id是sidebar的html标签的p和h2得到了不同的样式处理。
#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}

#sidebar h2 {
font-size: 1em;
font-weight: normal;
font-style: italic;
margin: 0;
line-height: 1.5;
text-align: right;
}


派生选择器

通过依据html标签元素在其位置的上下文关系来定义样式。

li标签的strong标签会受影响。
html代码
<p><strong>我是粗体字,不是斜体字,因为我不在列表当中,所以这个规则对我不起作用</strong></p>

<ol>
<li><strong>我是斜体字。这是因为 strong 元素位于 li 元素内。</strong></li>
<li>我是正常的字体。</li>
</ol>
css代码
li strong {
font-style: italic;
font-weight: normal;
}


除了上面选择器,还有类型选择器,后代选择器。类型选择器就是直接使用类型标签当作选择器,这样就作用于整个文件中同名类型标签。后代选择器是指使用嵌套在标签中的标签名作为选择器,也就是派生选择器,对整个文件页面的同名标签下同名的嵌套标签起作用。

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<style type="text/css">

p {
color: blue;
}

a {
text-decoration: underline;
}
h1 {
font-style: bold;
}
h1 a {
color: red;
}
</style>

</head>
<body>

<p>我是P标签1</p>
<a href="#">我是链接</a>
<h1>我是h1标签1<a href="#">百度</a></h1>
<h1>我是h1标签<a href="#">阿里</a></h1>
<p>我是P标签2</p>

</body>
</html>




实际上,我们经常需要组合多种一起使用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css