概述
CSS指层叠样式表(Cascading Style Sheet),定义如何显示HTML的元素。
多个样式可层叠在一起。
语法说明
规则:选择器+声明
selector {declaration1;declaration2;..}
选择器:需要改变样式的HTML元素
属性(property):设置的样式属性(style attribute)。属性对应值,被冒号分开,即属性:值
Tips:
- 使用分号;隔离声明
- 如果值为若干单词,要给值加“引号”
id选择器
- id选择器可以为标有特定id的HTML元素指定特定样式
- id选择器以#来定义
#red {color:red;}
<p id="red">这个段落是红色的。</p>
Tip:id属性只能在每个HTML文档中出现一次。只对标签后面的一个有效果。
类选择器
以一个点表示
如居中:.center {text-align:center}
<h1 class="center">
This heading will be center-aligned
</h1>
<p class="center">
This paragraph will also be center-aligned.
</p>
创建CSS
- 外部样式表
创建.css文件,并在HTML文件中使用<link>标签连接到样式表。如:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
其中mystyle.css是文件的相对位置。
Tip:不要在属性值和单位之间留空格。即margin-left: 20px,而非margin-left: 20 px
- 内部样式表
当单个文档需要特殊样式时可以使用。使用<style>标签在文档头部定义,如:
<head>
<style type="text/css">
hr {color: sienna;}
p {margin-left: 20px;}
body {background-image: url("images/back40.gif");}
</style>
</head>
HTML的块元素
div标签<div> </div>
代表块元素,且一个div占一行(即使代码写在一行,但有几个显示几个)。
使多个div放置在一行
使用{float:left}
和{float:right}
即 元素向左/右浮动
Tip:需在父元素(包括其的标签)中使用:{overflow:hidden}
修剪溢出
居中
{margin:0 auto;}
span标签<span> </span>
内联元素,可用作文本的容器。行内块元素。便于对行内的文字等进行设置。
边框
基本概念
内边距padding
h1 {
padding-top: 10px;
padding-right: 0.25em;
padding-bottom: 2ex;
padding-left: 20%;
}
外边距margin
h1 {margin : 10px 0px 15px 5px;}
顺序是从上开始,顺时针:上、右、下、左
块元素居中:{margin:0 auto;}
单边属性
h2 {
margin-top: 20px;
margin-right: 30px;
margin-bottom: 30px;
margin-left: 20px;
}
边框border
样式
标准{border-style: solid}
其他可以参考:http://www.w3school.com.cn/cssref/pr_border-style.asp
单边属性:{ border-style:solid;}
宽度
{border-width: 5px;}
px是像素单位
单边宽度:{border-width: 15px 5px 15px 5px;}
或者{ border-style:solid; border-top-width:15px; }
颜色border-color
p { border-style: solid; border-color: blue red; }
规定了上下边框是蓝色,左右边框是红色
单边颜色:{ border-style:solid; border-top-color:#ff0000; }
基本样式
背景
- 背景颜色
p {background-color: gray;}
- 背景图片
body {background-image: url(/i/eg_bg_04.gif);}
文本
对齐方式:
h1 {text-align:center}
h2 {text-align:left}
h3 {text-align:right}
链接
链接的四种状态:
- link - 普通的、未被访问的链接
- visited - 用户已访问的链接
- hover - 鼠标指针位于链接的上方
- active - 链接被点击的时刻
a:link {color:#FF0000;} /* 未被访问的链接 */
a:visited {color:#00FF00;} /* 已被访问的链接 */
a:hover {color:#FF00FF;} /* 鼠标指针移动到链接上 */
a:active {color:#0000FF;} /* 正在被点击的链接 */