Appearance
为网页添加样式 👌
1. 什么是 CSS
CSS(Cascading Style Sheets,层叠样式表)是一种用来描述 HTML 文档样式的语言。它控制网页的外观和布局,包括颜色、字体、间距、定位等视觉效果。
2. 术语解释
2.1 CSS 规则的基本结构
css
h1 {
color: red;
background-color: lightblue;
text-align: center;
}CSS 规则 = 选择器 + 声明块
2.2 选择器(Selector)
选择器用于选中需要应用样式的 HTML 元素。
元素选择器(标签选择器)
选中所有指定标签名的元素
css
/* 选中所有 p 元素 */
p {
font-size: 16px;
line-height: 1.5;
}
/* 选中所有 h1 元素 */
h1 {
color: blue;
font-weight: bold;
}ID 选择器
选中具有指定 id 属性值的元素(以 # 开头)
css
/* 选中 id="header" 的元素 */
#header {
background-color: #f0f0f0;
padding: 20px;
}
/* 选中 id="main-content" 的元素 */
#main-content {
width: 80%;
margin: 0 auto;
}对应的 HTML:
html
<div id="header">这是头部</div>
<div id="main-content">这是主要内容</div>类选择器
选中具有指定 class 属性值的元素(以 . 开头)
css
/* 选中所有 class="highlight" 的元素 */
.highlight {
background-color: yellow;
font-weight: bold;
}
/* 选中所有 class="btn" 的元素 */
.btn {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}对应的 HTML:
html
<p class="highlight">这是高亮文本</p>
<button class="btn">点击按钮</button>
<span class="highlight">这也是高亮文本</span>2.3 声明块(Declaration Block)
声明块出现在大括号 {} 中,包含一个或多个声明(属性)。
声明的组成
- 属性名:要设置的样式属性(如 color、font-size)
- 属性值:属性的具体值
- 分号:每个声明以分号结尾
css
.example {
/* 属性名: 属性值; */
color: red; /* 文字颜色 */
font-size: 18px; /* 字体大小 */
background-color: #f5f5f5; /* 背景颜色 */
margin: 10px; /* 外边距 */
padding: 15px; /* 内边距 */
}3. CSS 代码书写位置
- 内部样式表
将 CSS 代码书写在 HTML 文档的 <style> 元素中,通常放在 <head> 部分。
- 内联样式表(元素样式表)
直接在 HTML 元素的 style 属性中书写 CSS 样式。
注意:内联样式的优先级最高,但不推荐大量使用,因为它会使 HTML 代码变得混乱。
- 外部样式表(推荐)
当同一个元素被多种方式设置样式时,优先级从高到低为:
- 内联样式(style 属性)- 优先级最高
- 内部样式表(
<style>标签) - 外部样式表(
.css文件)- 优先级最低
