Skip to main content

CSS 详解

CSS(层叠样式表)用于控制网页的视觉表现,是前端开发的重要组成部分。本指南将介绍 CSS 的基础语法、常见用法、SCSS 的引入方法以及流行的 CSS 框架。


🧱 基础 CSS 语法

选择器 {
属性:;
}

示例:

h1 {
color: blue;
font-size: 24px;
}
常见选择器类型
  • *:通配符选择器
  • #id:ID 选择器
  • .class:类选择器
  • element:标签选择器
  • div > p:子元素选择器
  • a:hover:伪类选择器

🎨 常用属性分类

文本样式

p {
color: #333;
font-family: Arial, sans-serif;
text-align: center;
line-height: 1.6;
}

盒模型

.box {
width: 200px;
height: 100px;
padding: 10px;
margin: 20px;
border: 1px solid #ccc;
}

布局样式

.container {
display: flex;
justify-content: space-between;
align-items: center;
}

背景与边框

.card {
background-color: #f5f5f5;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

🧩 引入 CSS 的方式

<p style="color: red;">内联样式</p>

⚙️ 引入 SCSS / Sass

SCSS 是 CSS 的超集,支持变量、嵌套、Mixin 等高级特性。

1. 安装 Sass

npm install sass --save-dev

2. 编写 SCSS 代码

$primary-color: #3498db;

.button {
background-color: $primary-color;
&:hover {
background-color: darken($primary-color, 10%);
}
}

3. 编译 SCSS

npx sass styles.scss styles.css
tip

可使用 webpack、Vite 等工具自动编译 SCSS。


🧰 流行 CSS 框架

<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<button class="btn btn-primary">按钮</button>

✍️ 示例:完整页面结构

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<title>CSS 示例</title>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1 class="highlight">欢迎学习 CSS!</h1>
</body>
</html>

✅ 总结

  • CSS 控制网页的样式表现,常与 HTML 搭配使用;
  • 三种引入方式:内联、内部、外部;
  • SCSS 提供更强大的结构化样式编写;
  • 可以使用 Tailwind、Bootstrap 等流行框架加速开发。

📚 推荐链接