3.1 设置CSS样式的三种方式
3.1.1 在HTML标签内设置
仅对当前标签有效
<div style="border: 1px solid black;width: 100px; height: 100px;"> </div>
3.1.2 在head标签内设置
对当前页面有效
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.one {
border: 1px solid black;
width: 100px;
height: 100px;
background-color: lightgreen;
margin-top: 5px;
}
</style>
</head>
<body>
<div style="border: 1px solid black;width: 100px; height: 100px;"> </div>
<div class="one"> </div>
<div class="one"> </div>
<div class="one"> </div>
</body>
3.1.3 引入外部CSS样式文件
编辑CSS文件
.two {
border: 1px solid black;
width: 100px;
height: 100px;
background-color: yellow;
margin-top: 5px;
}
引入外部CSS文件
在需要使用这个CSS文件的HTML页面的head标签内加入:
<link rel="stylesheet" type="text/css" href="/aaa/pro01-HTML/style/example.css" />
于是下面HTML代码的显示效果是:
<div class="two"> </div>
<div class="two"> </div>
<div class="two"> </div>
3.2 CSS代码语法
- CSS样式由选择器和声明组成,而声明又由属性和值组成。
- 属性和值之间用冒号隔开。
- 多条声明之间用分号隔开。
- 使用/* … */声明注释。
3.3 CSS选择器
3.3.1 标签选择器
HTML代码:
<p>Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
CSS代码:
p {
color: blue;
font-weight: bold;
}
3.3.2 id选择器
HTML代码:
<p>Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
<p id="special">Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
<p>Hello, this is a p tag.</p>
CSS代码:
#special {
font-size: 20px;
background-color: aqua;
}
3.3.3 类选择器
HTML代码:
<div class="one"> </div>
<div class="one"> </div>
<div class="one"> </div>
CSS代码:
.one {
border: 1px solid black;
width: 100px;
height: 100px;
background-color: lightgreen;
margin-top: 5px;
}