被忽视的H5语义化标签
文章整理自:Write better HTML in 2021: the tips and tags you didn’t know you wanted
写html标签最常用的就是div
和span
了,这样带来的问题是写出来的html文档没有语义,还要写一推的样式去重置样式,html5推出来这么长时间了,各种语义化的标签也已经被各大浏览器所支持,这里推荐一些在工作中可能用到的语义化标签,希望别人读你代码时,能像读文档一样轻松。
语义化的标签
下面是一个语义页面结构页面:
<header>...</header>
<main>
<nav>...</nav>
<h1>...</h1>
<section>
<article>...</article>
<article>...</article>
</section>
<section>
<article>...</article>
<article>...</article>
</section>
<aside>...</aside>
</main>
<footer>...</footer>
不同等级的文本标签
small => 正常文本 => em => strong
It is <em>relevant</em>, but this is <strong>much more</strong>.
This is rather <small>unimportant</small>, though
文本被修改
删除文本可以使用<del/>
标签,修改后文本可以<ins />
标签。
In the end, I was <del>wrong</del><ins>right</ins>
联系方式
许多种类的数据可以在这里出现,如电子邮件、地址和电话
<address>
E-mail: <a href="mailto:me@mail.me">me@mail.me</a>
Carrot Street, 42 - 01010 My City
</address>
时间
建议使用以人类可读的时间为内容的时间标签,并在datetime属性中使用机器可读的时间。
Published: <time datetime="2020-12-20T20:00:00">Dec. 20th</time>
引用或参考
通常浏览器会给<q/>
标签的文本添加引号
My uncle said, <q cite="https://myuncle.org/famous-quotes">That's life, kid</q>
<blockquote>
<p>That's life, kids. Roll with it.</p>
<cite>
<a href="https://myuncle.org/famous-quotes">Famous quotes</a>, by my uncle
</cite>
</blockquote>
文本方向
使用<bdo/>
标签的 dir 属性可以改变文本方向
Text in arabic: <bdo dir="rtl">...</bdo>
键盘和计算机输出
显示键盘符号和计算机输出符号
When things seem bleak, just press <kbd>Alt</kbd> + <kbd>F4</kbd>
The computer will not say <samp>Access denied</samp> anymore, yay!
标记
This is very important and should be <mark>marked</mark>
列表描述
以前列表描述会使用dl
标签配合dt
+dd
标签,如果是简单的单行文本描述,可以使用<dfn>
标签,它是definitions简写
<dl>
<dt>Mario</dt>
<dd>An Italian plumber that wears red.</dd>
<dt>Luigi</dt>
<dd>An Italian plumber that wears green.</dd>
</dl>
<p><dfn>Mario</dfn> is an Italian plumber that wears red</p>
展开隐藏
通常我们想点击某个文本后,显示更多的隐藏文本,都是使用js才能实现,这里details
标签就可以不用写一行js代码实现效果,而且语义化好懂:
<details>
<summary>Working hours</summary>
Monday to Friday, 8:00 AM to 6:00 PM
</details>
图片加文本显示
很常见到展现形式,直接用语义化标签显示:
<figure>
<img src="cow.jpg" alt="A cow">
<figcaption>A cow in the pasture</figcaption>
</figure>
图片显示
更加丰富的图片选择
<picture>
<source srcset="cow-3x.jpg 3x, cow-2x.jpg 2x">
<source srcset="cow-print.jpg" media="print">
<img src="cow-1x.jpg" alt="A cow">
</picture>
拼音
汉字拼音也能用标签实现
<ruby>
汉 <rp>(</rp><rt>han</rt><rp>)</rp>
字 <rp>(</rp><rt>zi</rt><rp>)</rp>
</ruby>
rp标签是浏览器不支持显示的内容
进度条信息
meter 可以显示根据数值显示不同的进度颜色,但是各个浏览器表现形式差别很大,而且css不好控制
<meter low="3" high="7" max="10" value="5">5</meter>
<progress max="100" value="50">50%</progress>
输入框的提示文本列表
浏览器自带的输入框提示信息标签,语义化非常实用
<input type="text" name="shopping-item" list="common-groceries">
<datalist id="common-groceries">
<option value="Eggs">
<option value="Cucumber">
<option value="Peanuts">
<option value="Vodka">
</datalist>