1. CSS是什么?
CSS 指层叠样式表 (Cascading Style Sheets)
样式定义如何显示 HTML 元素
样式通常存储在样式表中
把样式添加到 HTML 4.0 中,是为了解决内容与表现分离的问题
外部样式表可以极大提高工作效率
外部样式表通常存储在 CSS 文件中
多个样式定义可层叠为一
2. CSS基本语法
selector {declaration1; declaration2; ... declarationN }
如 :h1 {color:red; font-size:14px;}
注:CSS的所有子元素(包括子元素的子元素...)继承父元素属性,除非对子元素再定义
3. CSS常用属性
CSS常用属性
属性 CSS名称 说明 颜色 color 文本属性 font-size 字体大小 font-family 字体 text-align 文本对齐 边框属性 border-style 边框样式 border-width 边框宽度 border-color 边框颜色 定位属性 top 上边距 left 左边距 width height z-index z轴索引,用于层
4. CSS的派生选择器:通过依据元素在其位置的上下文关系来定义样式
strong {
color: red;
}
h2 {
color: red;
}
h2 strong {
color: blue;
}
<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>
5. id 选择器可以为标有特定 id 的 HTML 元素指定特定的样式。以 "#" 来定义。可被用于派生选择器
#red {color:red;}
#green {color:green;}
<p id="red">这个段落是红色。</p>
<p id="green">这个段落是绿色。</p>
6. class选择器,以“.”定义。可被用于派生选择器
.center {text-align: center}
7. 属性选择器,“[]”表示,可以是[属性],也可以是[属性=值]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
//第一行为申明,指示 web 浏览器关于页面使用哪个 HTML 版本进行编写。
<html>
<head>
<style type="text/css">
[title=W3School]//属性选择器
{
border:5px solid blue;
}
</style>
</head>
<body>
<h1>可以应用样式:</h1>
<img title="W3School" src="/i/w3school_logo_white.gif" />
<br />
<a title="W3School" href="http://w3school.com.cn">W3School</a>
<hr />
<h1>无法应用样式:</h1>
<p title="greeting">Hi!</p>
<a class="W3School" href="http://w3school.com.cn">W3School</a>
</body>
</html>
8. 插入CSS样式表
a)外部样式表:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>
b)内嵌样式表:
<head>
<style type="text/css">
hr {color: sienna;}
p {margin-left: 20px;}
body {background-image: url("images/back40.gif");}
</style>
</head>
c)行内样式:不推荐
<p style="color: sienna; margin-left: 20px">
This is a paragraph
</p>
注:不同申明的属性重复时,会自动选择更具体的