WEB 学习第二天

CSS 简单介绍

  • CSS 指层叠样式表 (Cascading Style Sheets)
  • 样式通常存储在样式表中
  • 样式定义如何显示 HTML 元素
  • 外部样式表可以极大提高工作效率
  • 多个样式定义可层叠为一个

载入方法

  • 内联载入, 直接在标签中使用 style 属性, 多个键值对之间用空格分隔
    1
    <p style="font-size: 20px;">这是一个段落</p>
  • style 标签导入, 在 head 中使用 style 标签
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <head>
    <style>
    p {
    font-size: 30px;
    color: red;
    }
    </style>
    </head>
    <body>
    <p>这是一个段落</p>
    </body>
  • 外部文件载入, 使用 link 标签载入
    保证当前目录结构如下
    1
    2
    3
    4
    .
    ├── css
    │   └── style.css
    ├── index.html
    然后在 style.css 中写下如下内容

    style.css

    1
    2
    3
    p {
    font-size: 30px;
    }

    index.html

    1
    2
    3
    4
    5
    6
    <head>
    <link rel="stylesheet" href="./css/style.css">
    </head>
    <body>
    <p>这是一个段落</p>
    </body>

选择器(很重要)

标签选择器

1
2
3
4
5
6
7
p {
font-size: 30px;
}
div p {
font-size: 20px;
color: red;
}

第一个直接通过标签名进行选择, 第二个是只选择 div 内的 p 标签

ID 选择器

1
2
3
#sex {
color: blue;
}

以 # 号开头, 名字自己取, 注意需要在 html 中要应用此样式的元素加上对应的 id 属性

1
<div id="sex">this is sex id.</div>

Class 选择器

1
2
3
.ljguo {
background-color: pink;
}

以 . 开头, 名字自己取, 注意需要在 html 中要应用此样式的元素加上对应的 class 属性

1
<div class="ljguo">this is ljguo class.</div>

属性选择器

1
2
3
4
/* 选择带有 class 属性的元素 */
[class] {
font-weight: 700;
}

复合选择器(简单列举)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* 选择 div 中所有 class 为 ljguo 的元素 */
div.ljguo {
background-color: cyan;
}

/* 选择 div 中所有 id 为 sex 的元素 */
div#sex {
background-color: yellow;
}

/* 选择父元素为 div 的所有 p 元素 */
div>p {
text-align: center;
}

/* 选择紧跟 div 元素的首个 p 元素 */
div+p {
font-weight: 700;
}

/* 选择前面有 div 元素的每个 p 元素 */
div~p {
font-weight: 700;
}

/* 选择 target 属性值为 _blank 的元素 */
[target=_blank] {
font-size: 15px;
}

/* 鼠标点击 a 元素时 */
a:active {
color: cyan;
}

/* 鼠标悬停在 a 元素上时 */
a:hover {
color: red;
}

/* 焦点聚集时 */
input:focus {
background-color: magenta;
}
...

剩下的一些就是各种属性的积累了, 多查官网多使用熟练