Day6
●CSS的必要性
先看一个案例----使用span元素来编写
使用ide来开发css(myeclipse),因为myeclipse可以给我们提示功能。
<spanstyle=”font-size:30px;color:red;”>栏目一</span><br/>
从使用span元素我们可以看到,css的基本语法:
<元素名 style=”属性名:属性值;属性名2:属性值2;”/>
(元素可以是任意html支持的元素)
属性值:属性值要参考w3c给出的文档
●使用css可以统一网站的风格。
Css分类:
内部css、外部css
参考案例:
css代码如下:
/*.style1就是类选择器*/
.style1{
font-weight: bold;
font-size:20px;
background-color: pink;
color:black;
}
/*#style2就是一个id选择器*/
#style2{
font-size:30px;
background-color: silver;
color:black;
}
.style4{
font-style:italic;
text-decoration: underline;
color:green;
}
/*父子选择器*/
#style2 span{
font-style: italic;
color:red;
}
#style2 span span{
font-size: 50px;
}
/*html的选择器*/
/*前面为html的一个元素名称*/
/*注意优先级的问题*/
body{
color:orange;
}
a:LINK {
color:black;
text-decoration: none;
}
a:HOVER {
text-decoration: underline;
}
a:VISITED {
color:red;
}
/*使用通配符选择器,对外边距和内边距清零*/
/*不同的浏览器左边距和右边距不同,可能造成我们的页面在不同的浏览器打开出现错位*/
*{
/*margin: 0px;*/
/*margin四个值:上、右、下、左*/
/*margin三个值:上、左右、下*/
/*margin两个值:上下、左右*/
margin:10px 10px 0px;
/*padding的规范和margin一样*/
padding:0px;
}
html 代码如下:
<!-- Doctype:文档类型,用于指定dtd(说明当前这个html文件的版本) -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>css1</title>
<!-- 这个keywords是给搜索引擎看的 -->
<meta http-equiv="keywords" content="dell笔记本,怪味鸭,keyword3">
<!-- 对文件进行描述 -->
<meta http-equiv="description" content="this is my page">
<!-- 告诉浏览器文件的编码方式 -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- 引入css文件 -->
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<style type="text/css">
.style1{
font-size: 20px;
color:red;
font-weight:bold;
font-style:italic;
text-decoration: underline;
}
</style>
</head>
<body>
<!-- span是对元素的截断 -->
<span style="font-size:30px;color: blue;">栏目一</span><br/>
<span style="font-size:10px;color: red;font-style:italic;">栏目二</span><br/>
<span style="font-size: 20px;color:green;font-style: oblique;">栏目三</span><br/>
<span style="font-size: 15px;color:orange;font-weight: bold;">栏目四</span><br/>
<span class="style1">栏目六</span><br/><!-- 使用css统一风格 -->
<span class="style1">栏目六</span><br/>
<span class="style1">栏目六</span><br/>
</body>
</html>
运行效果如下:
●css的四种选择器
①类选择器
基本语法:
.类选择器名称{
属性名:属性值;
…
}
②id选择器
基本语法:
#类选择器名称{
属性名:属性值;
…
}
在html文件中如果要引用id选择器,则
<元素 id=“id选择器的名称”>内容</元素>
③html元素选择器
基本语法:
元素名{
属性名:属性值;
…
}
④通配符选择器
如果希望所有的元素都符合某一种样式,可以使用通配符选择器。
基本语法:
*{
属性名:属性值;
…
}
结论:当一个元素同时被id选择器、类选择器、html选择器修饰,则优先级是:
Id选择器 >类选择器> html选择器>通配符选择器
●选择器的深入讨论
- 父子选择器
需求:针对
<span id="style2">这是一则<span>非常重要</span>的新闻!</span>
/*父子选择器*/
#style2 span{
font-style:italic;
color:red;
}
Δ注意:1、子选择器标签是html可以识别的标签!
2、父子选择器可以有多级,但一般不超过3层!
3、父子选择器适用于id选择器、类选择器
②一个元素被id和class同时修饰的时候,id的优先级大于class的优先级
- 一个元素最多有一个id选择器,但是可以有多个类选择器
需求:希望新闻三是下划线,同时斜体
思路:(1)可以给新闻三配置一个Id选择器
(2)再指定一个class类选择器
Html中引用多个class的语法:Class =“style1 style2”
(1)在引用多个类选择器的时候,用空格隔开
(2)当style1和style2发生冲突时,Style以style1和style2在css文件中的位置为准,谁在后面以谁为准!
- 在有些css中,我们可以将多个class选择器、id选择器、html选择器,共同的部分提出,写在一起,这样的好处是:可以节省带宽
语法:
.类选择器1,类选择器2,类选择器3..{
共同属性:属性值;
…
}