1.css基本语法
1)css规则组成:选择器,一条或多条声明,声明由属性和值组成。例如:
h1 {color:red; font-size:14px;}
写成下面格式更方便阅读,最后一个元素可以加分号,也可以不加,建议加。例如:
h1{
color:red;
font-size:14px;
}
2)对选择器进行分组,一组的选择器可以共享一种声明,例如:
h1,h2,h3,h4{
color:red;
}
2.继承
通过 CSS 继承,子元素将继承最高级元素(在本例中是 body)所拥有的属性(这些子元素诸如 p, td, ul, ol, ul, li, dl, dt,和 dd)。例如:
body{
font-family: Verdana, sans-serif;
}
如果不希望某个子元素继承父元素的格式,就创建一个 针对这个子元素的格式。例如:
p{
font-family:Times,"Times New Roman",serif;
}
3.派生选择器
能根据上下文关系确认标签样式。例如:
strong{
color:red;
}
h strong{
color:green;
}
<h2>The strongly emphasized word in this subhead is<strong>green</strong></h2>
这里的green就是绿色的。
4.id选择器
为特定id的元素指定样式,以#显示。例如:
#red{
color:red;
}
<p id="red">这个段落显示为红色</p>
可以和派生选择器联合起来用。
5.类选择器
为特定的类的元素指定样式,以一个点号显示。例如:
.center{text-align:center}
<h1 class="center">This headline will be center-aligned.</h1>
可以和派生选择器联合起来用。
6.属性选择器
1)为拥有这个属性的元素设置属性选择器。例如:
[title]
{
color:red;
}
<h2 title="Hello world">Hello world</h2>
2)这个属性等于某个值的元素:
[title=test]
{
color:red;
}
<h2 title="test">Hello world</h2>
3)这个属性包含某个值的元素:
[title~=test]
{
color:red;
}
<a title="this is a test" href=“http://www.baidu.com”>test</a>
7.创建css
1)外部样式表
当样式被用于很多页面时,用外部样式表比较合适。
使用外部样式表方式:
<head>
<link ref=stylesheet type=text/css href="mystyle.css"/>
</head>
外部样式表mystyle.css要以css为扩展名,且文件内容不能包含html标签,它的文件内容例如:
h1{color:red;font-size:14px;}
p{font-family: Verdana, sans-serif;}
2)内部样式表
当样式被用于一个页面时,可以用内部样式表。
使用内部样式表方式:在html文件的头部用style标签标记:
<head>
<style type="text/css">
h1{color:red;font-size:14px;}
p{font-family: Verdana, sans-serif;}
</style>
</head>
3)内联样式表
当某个元素需要特别的样式时。
使用内联样式表方式:
<p style="color: blue; margin-left: 40px;font-size:30px”>
内部样式表及内联样式表例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">](http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"%3E);
<html>
<head>
<style type="text/css">
h1{color:Chocolate;}
h2{color:Coral;font-size:20px;}
h3,h4{color:CornflowerBlue;}
p{font-family: Verdana, sans-serif;color:#ff0099;background:HoneyDew;}
h2 strong {
color: blue;
}
#green {color:green;}
</style>
</head>
<body id="sidebar">
<h1>css study:</h1>
<h2 title="hello world">Good afternoon! <strong>!</strong></h2>
<p title="student hello">Let's start!</p>
<p style="color:BlueViolet; margin-left: 40px;font-size:30px;font-style: italic;"></p>
<p>Do you understand?</p>
<hr />
</body>
</html>
4)样式优先级:
内联样式>内部样式表>大于外部样式表>大于浏览器缺省值,所有的样式会根据优先级形成一个虚拟的样式表。
网友评论