前端语义化

在编程中,语义指的是一段代码的含义——例如“运行这行JavaScript代码会产生怎样的影响?”或者“这个HTML的元素有什么作用,扮演了什么角色”(而不只是“它看上去像是什么?”)

JavaScript中的语义

JavaScript中,考虑一个函数,该函数接受一个字符串参数,然后返回一个以该字符串为文本内容的<li>元素。如果该函数调用是build('Peach'),你会需要去看代码才能理解该函数做了什么吗,如果是createLiWithContent('Peach')呢?

CSS中的语义

CSS中,考虑给一个列表设置样式,li元素代表不同类型的水果。通过div>ul>li,你能知道DOM的那一部分会被选中吗?但是如果是.fruits_item呢?

HTML中的语义

HTML中,例如,<h1>元素是一个语义化元素,赋予了它包裹着的文本“这个页面中最高级别功能”的角色(或含义)。

<h1>This is a top level heading!</h1>

默认情况下,绝大多数浏览器的user agent stylesheet 将会赋予一个<h1>元素很大的字号尺寸从而使它看上去更像是一个标题(虽然你可以把它格式化为任何你想要的样式),但是更重要的是它的语义会被在很多地方以不同的样式被使用到,例如搜索引擎会把它包含的内容作为一个重要的关键词,从而影响这个页面在搜索结果中的排序,而且屏幕阅读器会使用它来帮助视障用户更好的使用这个页面。
另一方面,你可以通过样式(CSS)来让任何的元素看上去像是一个最高级别的标题,就像下面所展示的方法一样:

<span style="font-size:32px;margin:21px 0;">Is this a top level heading?</span>

这将会把这个元素渲染得像是一个最高级别的标题,但是它的值没有对应到“最高级别标题”这一语义,所以在此之上,它不会获得更多额外的描述(只是一个普通“span”元素而不是“最高级别标题”这一语义)。所以在恰当的需求下使用恰当的HTML元素是一个不错的主意。

HTML should be coded to represent the data that will be populated and not based on its default presentation styling. Presentation (how it should look), is the sole responsibility of CSS.

Some of the benefits from writing semantic markup are as follows:

  • Search engines will consider its contents as important keywords(搜索关键字) to influence the page’s search rankings(see SEO).
  • Screen readers can use it as a signpost to help visually impaired users(视障用户) navigate a page
  • Finding blocks of meaningful code is significantly easier(查找有意义的代码块) than searching though endless div s with or without semantic or namespaced classes.
  • Suggests to the developer the type of data will be populated(提示开发者填充的数据类型)
  • Semantic naming mirrors proper custom element/component naming(语义命名反映了符合规则的自定义元素/组件命名)

When approaching which markup to use, ask yourself, “What element(s) best describe/represent the data that I’m going to populate?” For example, is it a list of data?; ordered, unordered?; is it an article with sections and an aside of related information?; does it list out definitions?; is it a figure or image that needs a caption?; should it have a header and a footer in addition to the global site-wide header and footer?; etc.

语义化元素

以下是HTML5中的语义化元素(source)。

  • <article>
  • <aside>
  • <details>
  • <figcaption>
  • <figure>
  • <footer>
  • <header>
  • <main>
  • <mark>
  • <nav>
  • <section>
  • <summary>
  • <time>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值