第133集 CSS基础

1. CSS简介

CSS(Cascading Style Sheets,层叠样式表)是用于定义HTML页面样式和布局的语言。它与HTML一起工作,HTML定义页面的结构和内容,CSS定义页面的视觉表现。

1.1 CSS的历史

  • CSS 1.0(1996):第一个官方版本,定义了基本的样式属性
  • CSS 2.0(1998):增加了定位、z-index、媒体查询等功能
  • CSS 2.1(2004):修正了CSS 2.0中的错误,成为广泛使用的版本
  • CSS3(2011至今):模块化的版本,增加了许多新特性(圆角、阴影、渐变、动画等)

1.2 CSS的作用

  • 定义文本的样式(字体、大小、颜色、对齐方式等)
  • 设置元素的布局(宽度、高度、边距、间距等)
  • 添加背景、边框、阴影等视觉效果
  • 创建响应式设计,使页面在不同设备上都能良好显示
  • 实现动画和过渡效果

2. CSS的引入方式

2.1 内联样式(Inline Style)

直接在HTML元素的style属性中定义样式:

<p style="color: red; font-size: 18px;">这是一个红色的段落。</p>

优点:优先级高,可以覆盖其他样式
缺点:样式与结构混在一起,难以维护

2.2 内部样式表(Internal Style Sheet)

在HTML文档的&lt;head&gt;部分使用&lt;style&gt;标签定义样式:

<head>
    <style>
        p {
            color: blue;
            font-size: 16px;
        }
        h1 {
            color: green;
            text-align: center;
        }
    </style>
</head>

优点:样式与结构分离,便于维护单个页面
缺点:只对当前页面有效

2.3 外部样式表(External Style Sheet)

创建独立的CSS文件,然后在HTML文档中使用&lt;link&gt;标签引入:

<head>
    <link rel="stylesheet" href="styles.css">
</head>

styles.css文件内容:

p {
    color: purple;
    font-size: 14px;
}
body {
    background-color: #f0f0f0;
}

优点:样式与结构完全分离,便于维护多个页面
缺点:需要额外的HTTP请求

2.4 导入样式表(@import)

在CSS文件或内部样式表中使用@import规则导入其他CSS文件:

@import url("reset.css");
@import url("layout.css");

p {
    color: red;
}

注意:@import必须放在CSS文件的开头

3. CSS选择器

选择器用于选择要应用样式的HTML元素。

3.1 基础选择器

元素选择器

选择指定类型的HTML元素:

p {
    color: blue;
}

类选择器

选择具有指定class属性的元素:

.text-red {
    color: red;
}

HTML中使用:

<p class="text-red">这是红色文本。</p>
<div class="text-red">这也是红色文本。</div>

ID选择器

选择具有指定id属性的元素(id在页面中必须唯一):

#header {
    background-color: #333;
    color: white;
}

HTML中使用:

<div id="header">
    <h1>页面标题</h1>
</div>

通用选择器

选择所有元素:

* {
    margin: 0;
    padding: 0;
}

3.2 组合选择器

后代选择器

选择某个元素的所有后代元素:

.container p {
    color: green;
}

选择.container元素内的所有p元素。

子选择器

选择某个元素的直接子元素:

.container > p {
    color: blue;
}

只选择.container元素的直接子元素p

相邻兄弟选择器

选择某个元素之后紧邻的兄弟元素:

h1 + p {
    font-weight: bold;
}

选择h1元素之后紧邻的第一个p元素。

通用兄弟选择器

选择某个元素之后的所有兄弟元素:

h1 ~ p {
    color: gray;
}

选择h1元素之后的所有p兄弟元素。

3.3 伪类和伪元素

伪类

用于定义元素的特殊状态:

/* 链接的不同状态 */
a:link { color: blue; }       /* 未访问的链接 */
a:visited { color: purple; }  /* 已访问的链接 */
a:hover { color: red; }       /* 鼠标悬停时 */
a:active { color: green; }    /* 点击时 */

/* 表单元素状态 */
input:focus { border: 2px solid blue; }

/* 结构伪类 */
li:first-child { font-weight: bold; }
li:last-child { color: red; }
li:nth-child(2) { background-color: #f0f0f0; }

伪元素

用于在元素的特定位置插入内容或样式:

/* 在元素内容前插入 */
p::before {
    content: "★ ";
    color: red;
}

/* 在元素内容后插入 */
p::after {
    content: " ★";
    color: red;
}

/* 选择元素的第一个字母 */
h1::first-letter {
    font-size: 2em;
    color: blue;
}

/* 选择元素的第一行 */
p::first-line {
    font-weight: bold;
}

4. CSS常用属性

4.1 文本样式

/* 字体 */
p {
    font-family: "Microsoft YaHei", Arial, sans-serif;
    font-size: 16px;
    font-weight: normal; /* normal, bold, 100-900 */
    font-style: normal;  /* normal, italic, oblique */
    line-height: 1.5;    /* 行高 */
}

/* 文本颜色 */
h1 {
    color: #333;        /* 十六进制颜色 */
    color: rgb(51, 51, 51); /* RGB颜色 */
    color: rgba(51, 51, 51, 0.8); /* RGBA颜色,带透明度 */
    color: red;         /* 颜色名称 */
}

/* 文本对齐 */
.text-center {
    text-align: center; /* left, right, center, justify */
}

/* 文本装饰 */
a {
    text-decoration: none; /* none, underline, overline, line-through */
}

/* 文本转换 */
.uppercase {
    text-transform: uppercase; /* none, uppercase, lowercase, capitalize */
}

/* 文本缩进 */
.indent {
    text-indent: 2em;   /* 首行缩进2个字符 */
}

4.2 颜色和背景

/* 背景颜色 */
body {
    background-color: #f5f5f5;
}

/* 背景图片 */
.header {
    background-image: url("bg.jpg");
    background-repeat: no-repeat; /* repeat, repeat-x, repeat-y, no-repeat */
    background-position: center top; /* 背景图片位置 */
    background-size: cover; /* 背景图片大小:cover, contain, 具体尺寸 */
    background-attachment: fixed; /* scroll, fixed */
}

/* 简写形式 */
.header {
    background: #333 url("bg.jpg") no-repeat center top / cover fixed;
}

4.3 边框

/* 边框样式 */
.box {
    border-width: 2px;
    border-style: solid; /* solid, dashed, dotted, double, groove, ridge, inset, outset */
    border-color: #ccc;
}

/* 简写形式 */
.box {
    border: 2px solid #ccc;
}

/* 单独设置各边边框 */
.box {
    border-top: 1px solid red;
    border-right: 2px dashed blue;
    border-bottom: 3px dotted green;
    border-left: 4px double yellow;
}

/* 边框圆角 */
.box {
    border-radius: 5px; /* 所有角都是5px圆角 */
    border-radius: 5px 10px 15px 20px; /* 左上、右上、右下、左下 */
    border-radius: 50%; /* 圆形 */
}

4.4 盒模型

CSS中的每个元素都被视为一个盒子,包含内容区、内边距、边框和外边距。

.box {
    width: 200px;       /* 内容区宽度 */
    height: 100px;      /* 内容区高度 */
    padding: 20px;      /* 内边距 */
    border: 2px solid #ccc; /* 边框 */
    margin: 10px;       /* 外边距 */
}

/* 单独设置内边距 */
.box {
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
    /* 简写:上 右 下 左 */
    padding: 10px 20px 10px 20px;
    /* 简写:上下 左右 */
    padding: 10px 20px;
}

/* 单独设置外边距 */
.box {
    margin-top: 5px;
    margin-right: 10px;
    margin-bottom: 5px;
    margin-left: 10px;
    /* 简写:上 右 下 左 */
    margin: 5px 10px 5px 10px;
    /* 简写:上下 左右 */
    margin: 5px 10px;
}

/* 盒模型模式 */
.box {
    box-sizing: content-box; /* 默认值:width/height只包含内容区 */
    box-sizing: border-box; /* width/height包含内容区、内边距和边框 */
}

4.5 定位

/* 静态定位(默认) */
.static {
    position: static;
}

/* 相对定位 */
.relative {
    position: relative;
    top: 10px;
    left: 20px;
    /* 相对于元素原来的位置进行偏移 */
}

/* 绝对定位 */
.absolute {
    position: absolute;
    top: 0;
    right: 0;
    /* 相对于最近的已定位祖先元素进行定位 */
}

/* 固定定位 */
.fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    /* 相对于浏览器视口进行定位,不随页面滚动 */
}

/* 粘性定位 */
.sticky {
    position: sticky;
    top: 0;
    /* 在滚动到指定位置之前是相对定位,之后是固定定位 */
}

/* z-index:控制元素的堆叠顺序 */
.box1 {
    z-index: 1;
}
.box2 {
    z-index: 2; /* box2会显示在box1上方 */
}

4.6 显示和隐藏

/* 显示方式 */
.block {
    display: block;     /* 块级元素 */
}
.inline {
    display: inline;    /* 行内元素 */
}
.inline-block {
    display: inline-block; /* 行内块元素 */
}
.none {
    display: none;      /* 隐藏元素,不占据空间 */
}

/* 可见性 */
.hidden {
    visibility: hidden; /* 隐藏元素,但仍占据空间 */
}
.visible {
    visibility: visible; /* 显示元素 */
}

/* 溢出处理 */
.overflow {
    overflow: visible;  /* 默认值,溢出内容可见 */
    overflow: hidden;   /* 溢出内容隐藏 */
    overflow: scroll;   /* 显示滚动条 */
    overflow: auto;     /* 自动显示滚动条 */
}

5. CSS布局基础

5.1 块级元素和行内元素

  • 块级元素:默认占据整行空间,前后有换行

    • 示例:div, p, h1-h6, ul, ol, li, table, form
    • 可以设置width, height, margin, padding
  • 行内元素:只占据内容所需的空间,前后没有换行

    • 示例:span, a, strong, em, img, input
    • 不能设置width, height, 上下margin
  • 行内块元素:兼具行内元素和块级元素的特性

    • 示例:img, input, button
    • 可以设置width, height, margin, padding
    • 前后没有换行

5.2 浮动布局

/* 浮动元素 */
.float-left {
    float: left;
}
.float-right {
    float: right;
}

/* 清除浮动 */
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

5.3 Flexbox布局(弹性盒子)

Flexbox是CSS3中引入的一种灵活的布局方式,用于创建一维布局。

/* 容器属性 */
.flex-container {
    display: flex;
    flex-direction: row; /* row, row-reverse, column, column-reverse */
    flex-wrap: wrap;     /* nowrap, wrap, wrap-reverse */
    justify-content: flex-start; /* flex-start, flex-end, center, space-between, space-around, space-evenly */
    align-items: stretch; /* stretch, flex-start, flex-end, center, baseline */
    align-content: stretch; /* stretch, flex-start, flex-end, center, space-between, space-around */
}

/* 项目属性 */
.flex-item {
    flex-grow: 0;        /* 项目的放大比例 */
    flex-shrink: 1;      /* 项目的缩小比例 */
    flex-basis: auto;    /* 项目的初始大小 */
    flex: 0 1 auto;      /* 简写形式 */
    order: 0;            /* 项目的排列顺序 */
    align-self: auto;    /* 单个项目的对齐方式,覆盖align-items */
}

5.4 Grid布局(网格布局)

Grid是CSS3中引入的一种二维布局方式,用于创建网格布局。

/* 容器属性 */
.grid-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr; /* 定义列 */
    grid-template-rows: 100px 200px; /* 定义行 */
    grid-template-areas: /* 定义网格区域 */
        "header header header"
        "sidebar main main";
    gap: 10px; /* 网格间距 */
    grid-gap: 10px; /* 旧语法 */
}

/* 项目属性 */
.grid-item {
    grid-column: 1 / 3; /* 项目占据的列 */
    grid-row: 2 / 4;    /* 项目占据的行 */
    grid-area: header;  /* 项目所在的网格区域 */
}

6. CSS的层叠和继承

6.1 层叠(Cascade)

当多个CSS规则应用于同一个元素时,会根据以下规则确定最终应用哪个样式:

  1. 重要性(Importance):!important > 行内样式 > ID选择器 > 类选择器/属性选择器/伪类 > 元素选择器 > 通用选择器
  2. 特殊性(Specificity):选择器的特殊性值越高,优先级越高
    • 内联样式:1000
    • ID选择器:100
    • 类选择器/属性选择器/伪类:10
    • 元素选择器/伪元素:1
    • 通用选择器:0
  3. 源顺序(Source Order):在重要性和特殊性相同的情况下,后面定义的样式会覆盖前面的样式

6.2 继承(Inheritance)

某些CSS属性会从父元素继承到子元素:

  • 文本相关属性(color, font, text-align等)
  • 列表属性(list-style等)
  • 表格属性(border-collapse等)

可以使用inherit关键字强制继承父元素的样式,使用initial关键字恢复默认值。

.child {
    color: inherit; /* 继承父元素的颜色 */
    font-size: initial; /* 恢复默认字体大小 */
}

7. CSS响应式设计基础

7.1 媒体查询(Media Queries)

媒体查询允许根据不同的媒体类型和条件应用不同的样式:

/* 针对屏幕宽度小于600px的设备 */
@media screen and (max-width: 600px) {
    body {
        font-size: 14px;
    }
    .container {
        width: 100%;
        padding: 0 10px;
    }
}

/* 针对打印设备 */
@media print {
    body {
        font-size: 12pt;
        color: black;
    }
    .nav {
        display: none;
    }
}

7.2 视口(Viewport)

在HTML文档的&lt;head&gt;部分添加视口元标签,使页面在移动设备上能正确显示:

<meta name="viewport" content="width=device-width, initial-scale=1.0">
  • width=device-width:使页面宽度等于设备宽度
  • initial-scale=1.0:初始缩放比例为1

7.3 相对单位

使用相对单位可以使页面在不同设备上都能良好显示:

  • em:相对于父元素的字体大小
  • rem:相对于根元素(html)的字体大小
  • vw:视口宽度的1%
  • vh:视口高度的1%
  • %:相对于父元素的百分比

8. CSS3新特性

8.1 圆角(Border Radius)

.box {
    border-radius: 10px;
}

8.2 阴影(Box Shadow)

.box {
    box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
    /* 水平偏移、垂直偏移、模糊半径、阴影颜色 */
}

/* 文本阴影 */
h1 {
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

8.3 渐变(Gradients)

/* 线性渐变 */
.linear {
    background: linear-gradient(to right, red, blue);
    background: linear-gradient(45deg, red, blue);
}

/* 径向渐变 */
.radial {
    background: radial-gradient(circle, red, blue);
}

8.4 动画(Animation)

/* 定义动画 */
@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

/* 使用动画 */
.element {
    animation-name: fadeIn;
    animation-duration: 2s;
    animation-timing-function: ease;
    animation-delay: 1s;
    animation-iteration-count: infinite;
    animation-direction: alternate;
    animation-fill-mode: both;
}

/* 简写形式 */
.element {
    animation: fadeIn 2s ease 1s infinite alternate both;
}

8.5 过渡(Transition)

.element {
    transition-property: all;
    transition-duration: 0.3s;
    transition-timing-function: ease;
    transition-delay: 0s;
}

/* 简写形式 */
.element {
    transition: all 0.3s ease 0s;
}

/* 应用过渡 */
.element:hover {
    transform: scale(1.1);
    background-color: #333;
}

8.6 变换(Transform)

.element {
    transform: translate(10px, 20px); /* 平移 */
    transform: rotate(45deg); /* 旋转 */
    transform: scale(1.2); /* 缩放 */
    transform: skew(10deg, 5deg); /* 倾斜 */
    transform: matrix(1, 0, 0, 1, 10, 20); /* 矩阵变换 */
    transform-origin: center center; /* 变换原点 */
}

9. CSS最佳实践

  1. 使用外部样式表:将样式与结构分离,便于维护
  2. 使用语义化的选择器:提高代码的可读性和可维护性
  3. 使用简写属性:减少代码量
  4. 使用相对单位:创建响应式设计
  5. 使用CSS重置:消除不同浏览器的默认样式差异
  6. 组织CSS代码:使用注释和合理的结构组织代码
  7. 优化CSS性能:避免使用复杂的选择器,减少使用!important

10. 总结

CSS是网页开发的重要组成部分,通过各种属性可以创建出丰富的视觉效果和灵活的布局。掌握CSS的基础知识是学习Web开发的关键步骤之一。

下一集我们将学习JavaScript基础,了解如何为网页添加交互功能。

« 上一篇 HTML基础 下一篇 » JavaScript基础