Skip to content

CSS

如果说 HTML 负责“页面里有什么”,那 CSS 负责“页面长什么样”。

CSS 是做什么的

它主要控制:

  • 颜色
  • 大小
  • 间距
  • 边框
  • 布局
  • 定位

最简单的 CSS 示例

html
<style>
  h1 {
    color: blue;
    font-size: 32px;
  }
</style>

这表示:让页面里的 h1 变成蓝色,字号为 32 像素。

选择器

选择器决定“样式给谁用”。

标签选择器

css
p {
  color: red;
}

class 选择器

css
.title {
  color: green;
}

id 选择器

css
#box {
  width: 200px;
}

属性选择器

当你想根据属性选元素时会用到。

基础样式

字体样式

css
font-size: 16px;
font-weight: bold;
font-family: Arial;

文本样式

css
color: #333;
text-align: center;
line-height: 1.8;

背景样式

css
background-color: #f5f5f5;
background-image: url(bg.png);

盒子模型

盒子模型是 CSS 最核心的基础之一。

每个元素都可以理解成一个盒子,里面包括:

  • content:内容
  • padding:内边距
  • border:边框
  • margin:外边距
css
.card {
  width: 300px;
  padding: 20px;
  border: 1px solid #ddd;
  margin: 30px;
}

页面布局

浮动

早期布局经常用浮动。

清除浮动

如果不清浮动,父元素高度经常出问题。

定位

常见定位方式有:

  • static
  • relative
  • absolute
  • fixed

一个完整小示例

html
<div class="card">
  <h2>Python 学习卡片</h2>
  <p>适合零基础同学系统入门。</p>
</div>
css
.card {
  width: 320px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 12px;
  background: #fafafa;
}

.card h2 {
  margin-bottom: 12px;
  color: #1d4ed8;
}

学 CSS 时最重要的目标

  • 看懂选择器
  • 理解盒子模型
  • 能调文字、颜色、边距和布局

Built with VitePress.