HTML5时代的div

div,作为web标准化进程中大火大热的HTML标签,在完成了取代table布局的使命之后,在强调语义化的今天,开始成为被滥用得最多的标签。HTML5新增的标签中,有一大部分是为了取代HTML4里的div使用场景。比如:<header>、<footer>、<aside>、<section>、<nav>等。那么div还有存在的意义吗?如果有,又该在什么情况下使用呢?本文尝试对这个问题做一点分析。仅代表个人观点。

要考虑语义化的div,首先想到的当然是div的语义到底是什么。根据w3c的文档,div没有任何语义,它仅描述它所包含的成员,可以通过class、lang、title等属性来标注其语义。在使用上,它用来标注一组连贯的(关联的?)元素。

The div element has no special meaning at all. It represents its children. It can be used with the class, lang, and title attributes to mark up semantics common to a group of consecutive elements.

但是在这段文字下,w3c又用更为醒目的文字做了补充说明:

Authors are strongly encouraged to view the div element as an element of last resort, for when no other element is suitable. Use of the div element instead of more appropriate elements leads to poor accessibility for readers and poor maintainability for authors.

由此可见,并不提倡大量使用,到处使用div。在有更合适的元素下,使用div会导致可访问性和可维护性的降低。从这个意义上说,滥用div比恰当使用table的危害更大。因为table毕竟是有明确语义,有明确使用场景的。但是div依然是必不可少的,因为对于复杂的文档结构来说(尤其网页毕竟不是纯粹的文档),我们在网页重构过程中经常会遇到找不到恰当语义的元素的情况,这时候,使用div是没办法下的办法。但是,应该使用title、class、lang(文档没有提到id)等属性来赋予其语义。

比如:网页分为页眉(header)、主体(body)、页脚(footer),我们现在有了header、footer,缺没有对应于主体的标签(body已经用于文档内容的根元素了),这时候,用article或者section显然不符合语义,那么,选择div就是不错的选择。比如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
</head>
<body>
<header>
  <h1>文档标题</h1>
  <nav id="global">
<
a href="news.html">新闻</a> -
<a href="blog.html">博客</a> -
<a href="forums.html">论坛</a>
</
nav> <p>最后修改: <time>2009-04-01</time> </p> <nav id="local"> <h1>导航</h1> <ul> <li><a href="articles.html">所有文章</a></li> <li><a href="whatsnew.html">最新文章</a></li> <li><a href="elite.html">精华推荐</a></li> </ul> </nav> </header> <div> <article> <header> <h1>文章标题</h1> </header> <div> <p>Today I went to the beach and had a lot of fun.</p> ...更多内容... </div> <footer> <p>发表于 <time pubdate datetime="2009-10-10T14:36-08:00">星期二</time> .</p> </footer> </article> ...更多文章... </div> <footer> <p>Copyright © 2010 公司名称</p> <nav id="about"> <a href="about.html">About</a> - <a href="policy.html">Privacy Policy</a> - <a href="contact.html">Contact Us</a> </nav> </footer> </body> </html>

请关注这个HTML(来自w3c官方网站)结构,根据w3c的说明,div在这里用于包装页面上除了页眉和页脚之外的所有内容,以及包装文章中除了文章的头和尾之间的所有内容。w3c说明的原文如下:

Notice the div elements being used to wrap all the contents of the page other than the header and footer, and all the contents of the blog entry other than its header and footer.

对于div在HTML5中的应用,个人觉得这个文档结构已经给出了非常明确的例子。

小小的总结一下:div在HTML5中与在HTML4中的用途变化不大,除了已经有明确语义的新元素能够承担责任(比如header、footer、nav)之外,要将一组彼此关联的内容作为一个整体的时候,仍然适用div。

               

HTML5时代的div》上有1条评论

评论已关闭。