html标签属性

HTML 标签属性

HTML 标签属性

基本概念

  • 属性在 HTML 中非常重要,用于定义元素的行为、外观以及与其他元素的关系。
  • 属性通常写在开始标签中。

基本语法

1
<开始标签 属性名="属性值">

属性示例

1
2
<p id="describe" class="section">这是一个段落标签</p>
<a href="https://www.baidu.com">这是一个超链接</a>

属性大小写说明

  • 属性名称一般不区分大小写。
  • 属性值通常对大小写敏感,尤其是在文件路径、类名、图片名等场景下。
1
2
3
<img src="example.jpg" alt="">
<img SRC="example.jpg" alt="">
<img src="EXAMPLE.JPG" alt="">
  • 前两个写法在属性名层面通常可视为等价。
  • 第三个因为属性值不同,表示的资源路径可能也不同。

适用于大多数 HTML 元素的常见属性

class

  • class 用于给 HTML 元素定义一个或多个类名。
  • 常用于配合 CSS 进行样式控制,也可以在 JavaScript 中选择元素。

id

  • id 用于给元素定义唯一标识。
  • 一个页面中,同一个 id 理论上只应出现一次。

style

  • style 用于给元素设置行内样式。
  • 一般用于简单演示或临时样式,不建议大量使用。

示例

1
2
3
<h1 id="title"></h1>
<div class="nav-bar"></div>
<h2 class="nav-bar"></h2>

知识点总结

  • class 可以重复,适合给一类元素设置相同样式。
  • id 应保持唯一,适合标识某个特定元素。
  • style 是直接写在标签上的样式。

课堂示例代码

1
2
3
<h1 id="title"></h1>
<div class="nav-bar"></div>
<h2 class="nav-bar"></h2>

常见功能属性示例

a 标签的 href 和 target

  • href 用于指定链接地址。
  • target 用于指定链接打开方式。
1
2
3
4
5
<a href="https://hellolei.xin">访问我的网站</a>
<a href="https://hellolei.xin" target="_blank">在新窗口中打开</a>
<a href="https://hellolei.xin" target="_self">在当前窗口中打开</a>
<a href="https://hellolei.xin" target="_parent">在父窗口中打开</a>
<a href="https://hellolei.xin" target="_top">在顶层窗口中打开</a>

img 标签的 src、alt、width、height

  • src:指定图片路径。
  • alt:图片加载失败时显示的替代文本,也有利于无障碍和搜索引擎理解图片内容。
  • width:设置图片宽度。
  • height:设置图片高度。
1
2
3
<img src="https://hellolei.xin/images/logo.png" alt="HelloLei Logo">
<img src="头像.png" alt="我的头像" width="200" height="200">
<img src="头像.png" alt="我的头像">

课堂示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<a href="https://hellolei.xin">访问我的网站</a>
<a href="https://hellolei.xin" target="_blank">在新窗口中打开</a>
<br>
<a href="https://hellolei.xin" target="_self">在当前窗口中打开</a>
<hr>
<a href="https://hellolei.xin" target="_parent">在父窗口中打开</a>
<a href="https://hellolei.xin" target="_top">在顶层窗口中打开</a>
<hr>
<img src="https://hellolei.xin/images/logo.png" alt="HelloLei Logo">
<hr>
<img src="头像.png" alt="我的头像" width="200" height="200">
<hr>
<img src="头像.png" alt="我的头像">

知识点总结

  • 属性让标签具备更具体的功能和表现形式。
  • 学习 HTML 时,不仅要记标签,也要掌握常见属性。
  • a 标签常见属性是 hreftarget
  • img 标签常见属性是 srcaltwidthheight

复习表达

HTML 属性是写在开始标签中的附加信息,用来描述元素的功能和特性,基本语法是 属性名="属性值"。常见通用属性有 classidstyle,其中 class 可以复用,id 通常要求唯一。常见标签属性方面,链接标签 a 常用 hreftarget,图片标签 img 常用 srcaltwidthheight