前言
CSS样式用来美化页面。可以通过CSS各类选择器,指定作用于哪些组件。
引入样式表的三种方法
- 外部样式表,定义在外部文件
- 内部样式表 ,在
head
中定义样式 - 内联样式,在元素
style
中,规定样式
以下是三种的演示
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<head>
<style type="text/css">
body {background-color: red}
p {margin-left: 20px}
</style>
</head>
<p style="color: red; margin-left: 20px">
This is a paragraph
</p>
CSS语法
CSS 规则由两个主要的部分构成:选择器,以及一条或多条声明。
selector {declaration1; declaration2; ... declarationN }
CSS继承
例如我们在body
规定样式,则他的子元素也集成这些样式。
CSS选择器
派生选择器
根据文档的上下文关系来确定某个标签的样式。不管中间隔了多少层级,都会实现此类效果。对层级有要求的是 子元素选择器,只作用于直接子元素。
例如,希望列表中的 strong 元素变为斜体字
<!--派生选择器-->
li strong {
font-style: italic;
font-weight: normal;
}
<!--子元素选择器-->
h1 > strong {color:red;}
id选择器
id选择器以#
来定义,用来对指定id
的元素,设置样式。
#red {color:red;}
#green {color:green;}
<!--id选择器与派生结合-->
#sidebar p {
font-style: italic;
text-align: right;
margin-top: 0.5em;
}
类选择器
类选择器以一个点号.
显示,用来对指定class
的元素,设置样式。
.center {text-align: center}
<!--类选择器与派生一起使用-->
.fancy td {
color: #f60;
background: #666;
}
<!--表示只包括 类名为 fancy 的单元格-->
td.fancy {
color: #f60;
background: #666;
}
属性选择器
对有相应属性的元素,设置样式。格式[attribute]
[title]
{
color:red;
}
input[type="text"]
{
width:150px;
display:block;
margin-bottom:10px;
background-color:yellow;
font-family: Verdana, Arial;
}
相邻兄弟选择器
选择紧接在另一个元素后的元素,而且二者有相同的父元素。
<!--选择紧接在 h1 元素后出现的段落,h1 和 p 元素拥有共同的父元素-->
h1 + p {margin-top:50px;}
伪类
锚伪类 ,有如下几种
<!--未访问的链接-->
a:link {color: #FF0000}
<!--已访问的链接 -->
a:visited {color: #00FF00}
<!--鼠标移动到链接上-->
a:hover {color: #FF00FF}
<!--选定的链接-->
a:active {color: #0000FF}
其他的伪类还有,同级第一个元素:first-child
适用于各种标签的伪类
:onfocus
控件获得焦点
:active
点击控件的时候
:hover
当鼠标移动到某个控件上方
p:first-child {font-weight: bold;}
li:first-child {text-transform:uppercase;}