CSS的定义和作用
CSS(Cascading Style Sheets)是一种样式表语言,用于描述HTML或XML文档的呈现方式。它控制网页的布局、颜色、字体等视觉表现,实现内容与样式的分离。
CSS的基本定义
CSS全称为层叠样式表(Cascading Style Sheets),由W3C制定和维护。它通过选择器和声明块的结构来定义样式规则:
selector {
property: value;
/* 这是一个CSS注释 */
}
CSS的层叠特性体现在三个方面:
- 样式来源的优先级(用户代理样式、作者样式、用户样式)
- 选择器特异性计算
- 代码出现顺序
CSS的核心作用
实现内容与表现分离
传统HTML中样式直接写在元素上:
<!-- 旧式写法 -->
<h1 style="color: red; font-size: 24px;">标题</h1>
CSS将其分离为:
<!-- HTML -->
<h1 class="main-title">标题</h1>
/* CSS */
.main-title {
color: red;
font-size: 24px;
}
控制页面布局
CSS提供多种布局方式:
浮动布局
.float-left {
float: left;
width: 30%;
}
.float-right {
float: right;
width: 70%;
}
Flexbox布局
.container {
display: flex;
justify-content: space-between;
}
.item {
flex: 1;
}
Grid布局
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
响应式设计
通过媒体查询实现:
@media (max-width: 768px) {
.sidebar {
display: none;
}
.main-content {
width: 100%;
}
}
CSS选择器系统
基础选择器
/* 元素选择器 */
p { color: blue; }
/* 类选择器 */
.error { color: red; }
/* ID选择器 */
#header { background: #333; }
组合选择器
/* 后代选择器 */
article p { line-height: 1.6; }
/* 子选择器 */
ul > li { list-style: none; }
/* 相邻兄弟选择器 */
h2 + p { margin-top: 0; }
伪类和伪元素
/* 链接状态 */
a:hover { text-decoration: underline; }
/* 首字母 */
p::first-letter { font-size: 150%; }
CSS的盒模型
标准盒模型由内容区、内边距、边框和外边距组成:
.box {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 10px;
box-sizing: border-box; /* 切换盒模型计算方式 */
}
CSS动画与过渡
过渡效果
.button {
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #4CAF50;
}
关键帧动画
@keyframes slidein {
from { transform: translateX(100%); }
to { transform: translateX(0); }
}
.slide-element {
animation: slidein 1s forwards;
}
CSS预处理器
Sass示例
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
.button {
@include border-radius(5px);
}
CSS自定义属性
:root {
--main-bg-color: #f5f5f5;
}
.container {
background-color: var(--main-bg-color);
}
CSS模块化
现代前端框架中的CSS模块:
/* Button.module.css */
.primary {
background: var(--primary-color);
padding: 0.5rem 1rem;
}
import styles from './Button.module.css';
function Button() {
return <button className={styles.primary}>Click</button>;
}
CSS性能优化
选择器优化
/* 不推荐 */
div.container ul.nav li a { ... }
/* 推荐 */
.nav-link { ... }
避免重排重绘
/* 使用transform代替top/left */
.animate {
transform: translateX(100px);
}
CSS与无障碍
/* 隐藏内容但保持屏幕阅读器可访问 */
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
CSS的未来发展
容器查询
@container (min-width: 500px) {
.card {
display: grid;
grid-template-columns: 1fr 2fr;
}
}
嵌套语法
.card {
padding: 1rem;
&__title {
font-size: 1.2rem;
}
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:新兴Web标准对HTML5的影响
下一篇:CSS的发展历史