Files
SiMengWebSite_Notes/docs/notes/programming/web/basic-syntax/html2.md
Kawaxxxsaki 799551073c docs(web): 添加HTML基础语法第二课文档
新增HTML基础语法第二课文档,介绍div标签和class属性的基本概念及用法
2025-11-02 19:13:40 +08:00

144 lines
3.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: Web 前端基础第二课
createTime: 2025/11/2 18:25:48
permalink: /programming/web/basic-syntax/html2/
---
## 认识div标签
**什么是 <div>**
<div> 是 "division"(分区)的缩写,可以理解为网页中的"容器"或"盒子"。
想象一下搬家时的纸箱:
* 网页 = 整个房间
* <div> = 一个个纸箱
* 箱子里 = 可以放各种物品(文字、图片、按钮等)
## <div> 的基本特点
1. 块级元素
<div> 是块级元素,这意味着:
* 默认会占据整行的宽度
* 前后会自动换行
* 就像段落一样,每个<div>都会从新的一行开始
**<div> 本身没有特定含义,它只是用来分组和布局。**
## 为什么要使用 <div>
没有<div>的情况:
```html title='index.html'
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>仲夏夜之梦</title>
</head>
<body>
<h1>我的网站</h1>
<p>欢迎来到我的个人网站!</p>
<img src="photo.jpg" alt="我的照片">
<p>这是我的个人介绍...</p>
<button>联系我</button>
</body>
</html>
```
所有元素都堆在一起,很难分别控制样式。
使用 <div> 的情况:
```html title='index.html'
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>仲夏夜之梦</title>
</head>
<body>
<div class="header">
<h1>我的网站</h1>
<p>欢迎来到我的个人网站!</p>
</div>
<div class="content">
<img src="photo.jpg" alt="我的照片">
<p>这是我的个人介绍...</p>
</div>
<div class="footer">
<button>联系我</button>
</div>
</body>
</html>
```
这样我就可以分别控制每个部分的样式啦!
这个时候又有聪明的小朋友问了这个class是什么呀难道说是**起的名字!!**
太好了恭喜你答对了那么我们为什么要用class呢
## Class
Class 可以理解为给 HTML 元素起的"组名"或"类别名",让 CSS 能够精确地找到并美化特定的元素。
想象一个学校:
* HTML 元素 = 学生
* Class = 学生的身份(如"三年级一班"、"篮球队员"
* CSS = 老师,根据身份给学生安排不同的任务和服装
class基本用法此处就不举例了详情参照上面的代码。
如果没有class的情况
```html title='index.html'
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>仲夏夜之梦</title>
</head>
<body>
<h1>我的网站</h1>
<p>普通段落</p>
<p>个人介绍</p>
<p>重要提示</p>
<button>普通按钮</button>
<button>重要按钮</button>
</body>
</html>
```
如果我们想给"重要提示"和"重要按钮"设置特殊样式很难精确选择像之前我教的一样css直接用p或者h1来选择的话就无法区分具体每一段的区别了。
这时候就可以用class了
::: code-tabs
@tab index.html
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>仲夏夜之梦</title>
</head>
<body>
<h1>我的网站</h1>
<p class="normal">普通段落</p>
<p class="intro">个人介绍</p>
<p class="warning">重要提示</p>
<button class="normal-btn">普通按钮</button>
<button class="important-btn">重要按钮</button>
</body>
</html>
```
@tab style.css
```css
.warning {
color: red;
font-weight: bold;
}
.important-btn {
background-color: red;
color: white;
}
```
**现在自己动手尝试一下**