日期:2014-05-17  浏览次数:20734 次

html lang属性的疑惑
学习xhtml过程中,发现很多标签都可用lang属性,但是lang属性的用途是什么呢?

在《HTML XHTML CSS BIBLE 5th edition》一书中是这样讲解的:
Most tags support the lang attribute, which defines the language in which the content of the
tag should be displayed. For example, specifying en corresponds to English; en-US specifies the
United States version of English (as opposed to UK). This attribute has the same format as the
rest of the attributes: lang="en-US".


书中说是定义了标签内容使用的语言。但是在具体的应用中也没发现有什么用途一样?
------------test.html-----------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Test tag lang attribute</title>
</head>
<body>
<p lang="zh-CN">你好</p>
<p lang="en-US">hello</p>
<p lang="ja-JP">こんにちは</p>
<p lang="ko-KR">?????</p>

</body>
</html>

------------test1.html----------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Test tag lang attribute</title>
</head>
<body>
<p>你好</p>
<p>hello</p>
<p>こんにちは</p>
<p lang="ko-KR">?????</p>

</body>
</html>

test.html使用了lang属性来标示标签内容的语言。
test1.html没有使用lang属性来标示标签内用的语言。
注:为了防止UTF-8能显示所有语言的内容,故<meta>标签中设置为GBK。

但是结果发现,两个网页效果一样,都能正常显示。
是不是说明,这个lang属性没用呢?还是有什么其他可以使用的地方?
1 楼 我是新手 2012-07-22  
如果浏览器遵循W3C标准,lang属性可以用来定义样式。class定义了主要CSS,lang可以在class的基础上做出适当修改。

比如:
<style>
p{/*lang无效*/
   font-family: "宋体"
   font-size: 14px;
   color: #F00;
}
p:lang(zh-CN){/*lang="zh-CN"*/
   font-family: "宋体"
}
p:lang(en-US){/*lang="en-US"*/
   font-family: Arial
}
</style>

这里p标签的主要CSS只定义了字体大小和颜色,然后就需要通过标签的lang属性来确定字体。
lang属性的好处呢,就在于它的CSS继承性,或许p标签需要定义很多样式,但不同的语言(其实也不只是语言)可能需要变动少量的样式,如果把这些样式分开定义,可能就会似的CSS很冗长,浪费用户的流量和内存。