← 返回上一页

第1章: CSS 简介与引入方式

了解 CSS 是什么以及如何在 HTML 中使用 CSS

💻 在线CSS样式编辑器

在这里实时编写CSS样式,立即查看效果:

📝 CSS代码区

📄 HTML代码区

👁️ 实时预览

🔢 CSS优先级计算器

输入选择器,自动计算优先级分数:

📝 输入选择器

🎯 计算结果

输入选择器后自动计算...

📊 优先级规则

ID选择器 (#id)

→ 100分

类/伪类 (.class, :hover)

→ 10分

元素/伪元素 (div, ::before)

→ 1分

🎯 CSS知识测验

测试你对CSS基础的理解:

问题 1:以下哪种CSS引入方式优先级最高?

问题 2:选择器 #nav .item a 的优先级分数是?

问题 3:CSS注释的正确写法是?

什么是 CSS?

CSS (Cascading Style Sheets,层叠样式表) 是用于描述 HTML 文档样式的语言。它控制网页的外观和布局。

CSS 的作用

💡 提示: CSS 让我们能够将内容(HTML)和样式(CSS)分离,使代码更易维护。

CSS 基本语法

CSS 规则由选择器和声明块组成:

选择器 { 属性: 值; 属性: 值; } /* 示例 */ p { color: blue; font-size: 16px; }

🔍 CSS语法结构可视化

p { color : blue ; font-size : 16px ; }

👆 点击上方各部分查看详细解释

语法组成

CSS 引入方式

有三种方式在 HTML 中使用 CSS:

1. 内联样式(Inline Style)

直接在 HTML 元素的 style 属性中编写 CSS。

<p style="color: red; font-size: 20px;">这是红色文本</p>

📝 实时编辑内联样式:

这是内联样式演示文本

优点:优先级最高,可以快速测试样式

缺点:难以维护,不能复用,不推荐大量使用

2. 内部样式(Internal Style)

在 HTML 文档的 <head> 部分使用 <style> 标签。

<head> <style> p { color: blue; font-size: 18px; } </style> </head>

优点:适合单页面的样式

缺点:不能在多个页面间共享

3. 外部样式(External Style)

创建独立的 .css 文件,在 HTML 中通过 <link> 标签引入。

<!-- HTML 文件 --> <head> <link rel="stylesheet" href="styles.css"> </head>
/* styles.css 文件 */ p { color: green; font-size: 16px; }

优点:可复用,易维护,推荐使用

缺点:需要额外的 HTTP 请求

📄 内联样式

优先级:最高

复用性:❌ 无

维护性:❌ 差

⚠️ 不推荐

📝 内部样式

优先级:中等

复用性:⚠️ 单页

维护性:⚠️ 一般

💡 适合单页

📁 外部样式

优先级:最低

复用性:✅ 全站

维护性:✅ 好

✅ 推荐使用

三种引入方式对比演示

内联样式

这段文字使用内联样式:红色、20px、加粗

内部样式

这段文字使用内部样式:蓝色、18px、斜体

外部样式

这段文字模拟外部样式:绿色、16px(本页面的样式来自外部 CSS)

CSS 优先级

当多个样式规则应用于同一元素时,优先级决定哪个样式生效。

📊 优先级权重可视化

!important
∞ 无限大
内联样式
1000
ID选择器
100
类/伪类/属性
10
元素/伪元素
1
通配符 *
0

🧮 优先级计算器

输入选择器,计算其优先级权重:

优先级顺序(从高到低)

  1. !important 声明
  2. 内联样式(style 属性)
  3. ID 选择器(#id)
  4. 类选择器、属性选择器、伪类(.class、[attr]、:hover)
  5. 元素选择器、伪元素(p、::before)
  6. 通配符选择器(*)
/* 优先级示例 */ p { color: rgba(255, 255, 255, 0.95); } /* 优先级最低 */ .text { color: blue; } /* 优先级较高 */ #special { color: green; } /* 优先级更高 */ <p style="color: red;">...</p> /* 优先级最高 */ p { color: yellow !important; } /* !important 最高 */
⚠️ 注意: 避免过度使用 !important,它会使样式难以维护和调试。

🎯 互动练习:CSS 优先级

下面的文本应用了多个样式规则,观察哪个生效:

/* CSS 样式规则 */ #priority-demo { color: green; /* ID选择器 - 优先级:100 */ } .priority-class { color: blue; /* 类选择器 - 优先级:10 */ } p.priority-element { color: orange; /* 元素+类选择器 - 优先级:11 */ }
<!-- HTML 代码 --> <p class="priority-class" id="priority-demo" style="color: red;"> 这段文字应用了多个样式... </p>

这段文字应用了多个样式:元素选择器(橙色)、类选择器(蓝色)、ID选择器(绿色)、内联样式(红色)

🎯 优先级计算:

  • 内联样式 (style="color: red;") - 优先级:1000 ✅ 最高
  • ID选择器 (#priority-demo) - 优先级:100
  • 类选择器 (.priority-class) - 优先级:10
  • 元素选择器 (p) - 优先级:1

结果:文字显示为红色,因为内联样式的优先级最高!

CSS 注释

使用 /* */ 添加注释,注释不会被浏览器渲染。

/* 这是单行注释 */ /* * 这是多行注释 * 可以写多行说明 */ p { color: blue; /* 设置文字颜色为蓝色 */ }

本章小结

← 返回上一页 下一章:选择器 →
`; iframeDoc.open(); iframeDoc.write(fullHtml); iframeDoc.close(); } function resetCssEditor1() { document.getElementById('cssEditor1').value = defaultCss1; document.getElementById('htmlEditor1').value = defaultHtml1; runCssEditor1(); } // 页面加载时运行默认代码 window.addEventListener('load', runCssEditor1); // 语法高亮解释 function highlightSyntax(type) { const explanations = { selector: { title: '🎯 选择器 (Selector)', content: '选择器用于指定要设置样式的HTML元素。常见选择器包括:元素选择器(p, div)、类选择器(.class)、ID选择器(#id)等。', color: '#667eea' }, property: { title: '📝 属性 (Property)', content: '属性是要改变的样式特性,如color(颜色)、font-size(字体大小)、margin(外边距)等。每个属性都有特定的可用值。', color: '#10b981' }, value: { title: '💎 值 (Value)', content: '值是属性的具体设置,如color的值可以是red、blue、#ff0000等。不同属性接受不同类型的值。', color: '#fbbf24' } }; const info = explanations[type]; document.getElementById('syntaxExplanation').innerHTML = `
${info.title}

${info.content}

`; } // 内联样式实时演示 function updateInlineDemo() { const input = document.getElementById('inlineStyleInput').value; const demo = document.getElementById('inlineStyleDemo'); demo.style.cssText = input; } // 优先级计算器 function calculatePriority() { const input = document.getElementById('priorityCalculator').value.trim(); const resultDiv = document.getElementById('priorityResult'); if (!input) { resultDiv.style.display = 'none'; return; } resultDiv.style.display = 'block'; // 计算ID选择器数量 const idCount = (input.match(/#[a-zA-Z][\w-]*/g) || []).length; // 计算类选择器、属性选择器、伪类数量 const classCount = (input.match(/\.[a-zA-Z][\w-]*/g) || []).length; const attrCount = (input.match(/\[[^\]]+\]/g) || []).length; const pseudoClassCount = (input.match(/(? m !== ':hover' || true).length; // 计算元素选择器数量 const elementCount = (input.match(/(? 0) explanation += `${ids}个ID选择器 `; if (classes > 0) explanation += `${classes}个类/伪类/属性选择器 `; if (elements > 0) explanation += `${elements}个元素选择器`; document.getElementById('priorityExplanation').textContent = explanation; } // CSS优先级计算器 function calculateSpecificity() { const input = document.getElementById('selectorInput1').value.trim(); const resultDiv = document.getElementById('specificityResult'); if (!input) { resultDiv.innerHTML = '

输入选择器后自动计算...

'; return; } // 计算ID选择器数量 (#id) const idCount = (input.match(/#[a-zA-Z][\w-]*/g) || []).length; // 计算类选择器、属性选择器、伪类数量 (.class, [attr], :hover) const classCount = (input.match(/\.[a-zA-Z][\w-]*/g) || []).length; const attrCount = (input.match(/\[[^\]]+\]/g) || []).length; const pseudoClassCount = (input.match(/(?
${ids}
ID选择器
× 100
${classes}
类/伪类
× 10
${elements}
元素
× 1
优先级总分
${total}
`; } // CSS知识测验 const cssQuizAnswers1 = { css_q1: 'D', css_q2: 'A', css_q3: 'B' }; const cssQuizExplanations1 = { css_q1: '!important 声明具有最高优先级,甚至可以覆盖内联样式。但应谨慎使用。', css_q2: '#nav (100分) + .item (10分) + a (1分) = 111分。ID选择器100分,类选择器10分,元素选择器1分。', css_q3: 'CSS使用 /* 注释内容 */ 的格式进行注释,支持单行和多行注释。' }; function checkCssQuiz1() { let score = 0; let total = Object.keys(cssQuizAnswers1).length; for (let question in cssQuizAnswers1) { const answerDiv = document.getElementById('css_answer' + question.split('_')[1]); const selected = document.querySelector(`input[name="${question}"]:checked`); if (selected) { if (selected.value === cssQuizAnswers1[question]) { score++; answerDiv.style.background = 'rgba(16, 185, 129, 0.2)'; answerDiv.style.border = '1px solid #10b981'; answerDiv.innerHTML = `✅ 正确! ${cssQuizExplanations1[question]}`; } else { answerDiv.style.background = 'rgba(239, 68, 68, 0.2)'; answerDiv.style.border = '1px solid #ef4444'; answerDiv.innerHTML = `❌ 错误! 正确答案:${cssQuizAnswers1[question]}。${cssQuizExplanations1[question]}`; } answerDiv.style.display = 'block'; } else { answerDiv.style.background = 'rgba(251, 191, 36, 0.2)'; answerDiv.style.border = '1px solid #fbbf24'; answerDiv.innerHTML = `⚠️ 未选择答案`; answerDiv.style.display = 'block'; } } const resultDiv = document.getElementById('cssQuizResult1'); resultDiv.style.display = 'block'; const percentage = Math.round((score / total) * 100); let message, bgColor; if (percentage === 100) { message = '🎉 太棒了!全部正确!你已经掌握了CSS基础知识!'; bgColor = 'rgba(16, 185, 129, 0.2)'; } else if (percentage >= 60) { message = '👍 不错!你掌握了大部分内容,继续加油!'; bgColor = 'rgba(59, 130, 246, 0.2)'; } else { message = '💪 还需要多练习!建议重新学习本章内容。'; bgColor = 'rgba(239, 68, 68, 0.2)'; } resultDiv.style.background = bgColor; resultDiv.innerHTML = `

📊 测验结果

得分:${score}/${total} (${percentage}%)

${message}

`; } // 原有的优先级演示功能 let priorityVisible = false; function togglePriority() { const display = document.getElementById('priorityDisplay'); priorityVisible = !priorityVisible; display.style.display = priorityVisible ? 'block' : 'none'; if (priorityVisible) { setTimeout(() => { document.getElementById('demo2').style.color = 'blue'; }, 500); setTimeout(() => { document.getElementById('demo3').style.color = 'green'; document.getElementById('demo3').id = 'priority-id'; }, 1000); } }