简体   繁体   English

我应该使用 id 还是 class 来“指示” Tailwind.css 中 HTML 元素的用途?

[英]Should I be using an id or a class to "signal" the purpose of an HTML element in Tailwind.css?

The context :上下文

I have a complex html structure on a header of a website built with Alpine.js and Tailwind.css on the frontend.我在前端使用Alpine.js 和 Tailwind.css构建的网站的 header 上有一个复杂的 html 结构。

"Complex structure", as in: “复杂结构”,如:

<header class="BODY-HEADER">
    <div class="NOTIFICATION-WRAPPER grid md:grid-cols ... id-cols-3 t ... font-medium ... p-4">
        <div class="TOP-MSG my-auto ... inline-block hidden md:block ... text-right">
            <span class="EMAIL">
                <svg>...</svg>
                <span class="ml-1"> 
                    email @ example . com
                </span>
            </div>
            <div class="CONTACT-INFO flex">
                <span class="PHONE mr-4">
                    <svg>...</svg>
                    <a class="ml-1">...</a>
                </span>
            </div>
            <div class="NOTIFICATION m-auto md:my-auto ... text-center ... lg:ml-0">
                Subscribe to our newsletter. 
            </div>
        </div>
        <script>
    function initializeHdr() {
      return {
            ...
        },
        menu: initializeHdrNav()
      }
    }

    function initializeCompareHdr() {
      return {
            ...
          }
        }
      }
    }
  </script>
        <div 
       x-data="sticky header logic here" 
       @scroll.window="scroll sticky header trigger here"
  >
    <div 
         id="js-sticky-header" 
         :class="{ 'lg:fixed': showStickyHdr == true }" 
         class="header-sticky top-0 z-10 w-full"
    >
      <div 
           id="menu-wrapper" 
           x-data="initializeHdr()" 
           @keydown.window.escape="searchModalOpen = false;" 
           @private-content-loaded.window="getAllData(event.detail.data)" 
           class="z-10 w-full ... bg-container-dark"
      >
                    <nav id="MAIN-MENU" class="grid grid ... justify-between items-center ... ">
                        <div class="LOGO-WRAPPER md:w-40 px-5 ... 0 mx-auto ... ">
                            <!-- the logo -->
                            <a href="url to local environment's home here" title="" aria-label="the logo label here">

<!-- etc... another 1400 lines are all part of the MAIN NAVIGATION structure -->

There are several groups of links in the navigation, sub-navs if you'd like.如果您愿意,导航中有几组链接,子导航。 And the navigation itself is different on mobile and on desktop, implemented as two wrapping divs.并且导航本身在移动设备和桌面上是不同的,实现为两个包装 div。 One wrapping div wraps the mobile, the other wraps the desktop, but there are also other elements wrapping both divs, then some other content above the navigation, then additional info in the same header where the navigation "lives".一个包装 div 包装移动设备,另一个包装桌面,但还有其他元素包装两个 div,然后是导航上方的一些其他内容,然后是导航“存在”的同一 header 中的附加信息。

TL;DR: It's a complex HTML structure with multiple layouts on different viewports and with multiple levels of nesting (all together, the resulting HTML is 1500 lines of code). TL;DR:这是一个复杂的 HTML 结构,在不同的视口上具有多个布局,并且具有多个嵌套级别(总而言之,生成的 HTML 是 1500 行代码)。

The question :问题

Initially, a co-worker used a CSS class to signal the "meaning" of the specific section, for example:最初,一位同事使用 CSS class 来表示特定部分的“含义”,例如:

<nav class="MAIN-MENU grid grid-cols-3 2xl:grid-cols-4 items-center px-5 justify-between">

I've put the "offending" code in ALL-CAPS, so that it's easier to spot in this question.我已将“违规”代码放在全大写中,以便更容易在这个问题中发现。

I'm trying to make the intent of the nested elements more obvious by "signalling" the functionality of the elements.我试图通过“发出信号”元素的功能来使嵌套元素的意图更加明显。

The explanation of user AndyJamesM on how/when to use id's and classes and the comparison of HTML4 and HTML5 standards is useful but doesn't really apply in this case.用户 AndyJamesM 关于如何/何时使用 id 和类的解释以及 HTML4 和 HTML5 标准的比较很有用,但在这种情况下并不真正适用。

Thus, I've taken a different approach, since it's a single unique element, so I've moved it to the id attribute, like this:因此,我采用了不同的方法,因为它是一个唯一的元素,所以我将它移到了id属性中,如下所示:

<nav
  id="main-menu"
  class="grid grid-cols-3 2xl:grid-cols-4 items-center px-5 justify-between"
>

Both the id="main-menu" and the class="main-menu don't have any styling, they're just there for "naming purposes" and for readability, so that when people glance over the code, they immediately know what's happening. id="main-menu"class="main-menu都没有任何样式,它们只是为了“命名目的”和可读性,所以当人们浏览代码时,他们会立即知道发生了什么。

Logically, I would say that it's better to use the id="main-menu" because:从逻辑上讲,我会说最好使用id="main-menu"因为:

  1. It's a single element on the page, so I'm signalling uniqueness它是页面上的单个元素,所以我表示它的唯一性
  2. It's extracted from the class attribute, because the class attribute already has too much noise from other Tailwind classes.它是从class属性中提取的,因为class属性已经有太多来自其他 Tailwind 类的噪音。
  3. It's setting up the stage for possibly hooking up with some JS (Alpine.js) functionality down the road.它正在为将来可能与一些 JS (Alpine.js) 功能挂钩奠定基础。

As far as keeping an empty class name to signal the purpose, I cannot see the benefit of that approach.至于保留一个空的 class 名称来表示目的,我看不出这种方法的好处。 I've listed the 3 arguments against it, in the bullet points above.我在上面的要点中列出了 3 个 arguments。

I can't find counter arguments where I would favor the use of class names as signals for intent.我找不到计数器 arguments ,我倾向于使用 class 名称作为意图信号。

Is there any clearly defined best practice to follow when making this decision?在做出此决定时,是否有任何明确定义的最佳实践可以遵循?

I have a co-worker advocating for use of classes as the answer.我有一位同事主张使用课程作为答案。 I don't find it logical, but he's adamant about his viewpoint based on seniority in the company, and a hunch.我觉得这不合逻辑,但他坚持自己基于公司资历和预感的观点。 The argument that I get is that id's should be avioded, but why?我得到的论点是应该避免 id ,但是为什么呢?

Edit: One possible viable reason to not use id for naming: We're "signalling" the use of JS - when in fact there is none.编辑:不使用id命名的一个可能的可行原因:我们正在“发出”使用 JS 的“信号”——实际上没有。 This can be "cleaned up" by appending js- in front of every id value that is actually using JS, but this also means additional time wasted on updating the code, while not being sure if this is the best approach.这可以通过在每个实际使用 JS 的id值前面附加js-来“清理”,但这也意味着在更新代码上浪费了额外的时间,同时不确定这是否是最好的方法。

Is there a different approach than the two given options?是否有与两个给定选项不同的方法?

One possible alternative is HTML comments.一种可能的替代方法是 HTML 注释。 This might be the best choice it seems.这似乎是最好的选择。

The aria-labelledby approach also seems like a step in the right direction. aria-labelledby方法似乎也是朝着正确方向迈出的一步。

Another thing that comes to mind is using custom data attributes.想到的另一件事是使用自定义数据属性。 Since they don't have to have a value, it could be as simple as this:由于它们不必具有值,因此可以像这样简单:

<nav data-nested-desktop-sub-nav>

But still, the question remains: what would be "the best" approach?但是,问题仍然存在:什么是“最好的”方法?

In HTML 4 ID's were used to add semantics (meaning / naming) to elements.在 HTML 中,4 个 ID 用于向元素添加语义(含义/命名)。 In html5 new tags were introduced to provide better semantics "out of the box"在 html5 中引入了新标签以提供更好的“开箱即用”语义

I'm trying to make the intent of the nested elements more obvious by "signalling" the functionality of the elements.我试图通过“发出信号”元素的功能来使嵌套元素的意图更加明显。

The nav element already does this by giving the element meaning and states that the links inside it are MAIN navigation links and screen readers know the role of this element is for navigation. nav 元素已经通过赋予元素含义来做到这一点,并声明其中的链接是主要导航链接,屏幕阅读器知道该元素的作用是导航。

So using a <nav> element which provides meaning/semantics already as its intended to be used with the main navigation elements as per html5 specs and perhaps this is inside a <header> too.因此,根据 html5 规范,使用已提供含义/语义的<nav>元素与主要导航元素一起使用,也许这也在<header>内。 Structurally this markup provides solid meaning as it is a main navigation inside a site header.在结构上,这个标记提供了坚实的意义,因为它是站点 header 内的主要导航。 In this case I do not see any value in adding an ID purely for identification.在这种情况下,我认为添加一个纯粹用于识别的 ID 没有任何价值。

"It's not necessary for all links to be contained in a <nav> element. <nav> is intended only for major block of navigation links; typically the <footer> element often has a list of links that don't need to be in a <nav> element." “没有必要将所有链接都包含在<nav>元素中。 <nav>仅用于导航链接的主要块;通常<footer>元素通常具有不需要的链接列表<nav>元素。”

See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav#usage_notes请参阅: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav#usage_notes

Furthermore to promote accessibility if that's the concern use "aria-labelledby"此外,如果担心的话,为了提高可访问性,请使用“aria-labelledby”

"A document may have several <nav> elements, for example, one for site navigation and one for intra-page navigation. aria-labelledby can be used in such case to promote accessibility, see example." “一个文档可能有多个<nav>元素,例如,一个用于站点导航,一个用于页面内导航。在这种情况下,可以使用 aria-labelledby 来提高可访问性,请参见示例。”

Using <header> and <nav> provide far more value than any ID ever could.使用<header><nav>提供的价值远远超过任何 ID。 They help define the document outline by creating content sections and add value to screen readers for accessibility.它们通过创建内容部分来帮助定义文档大纲,并为屏幕阅读器增加可访问性的价值。

A nav in a header creates an outline hierarchy as follows: header 中的导航创建大纲层次结构,如下所示:

- Header
    - Main Nav

Using ID on the nav adds little value like it used to unless you are using it for hooking up to JS.在导航上使用 ID 不会像以前那样增加任何价值,除非您使用它来连接 JS。 A class hanging out there just for naming adds nothing else and is arguably completely pointless.只是为了命名而挂在那里的 class 没有添加任何其他内容,并且可以说是完全没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 tailwind.css 创建与主要内容一起滚动的侧边栏? - How do I create a Sidebar which scrolls with the main content using tailwind.css? 使用 Tailwind-CSS 在 HTML 元素中删除或添加 class 后浏览器未更新 - Browser not updating after remove or add a class in HTML element using Tailwind-CSS 无法居中绝对 position (Tailwind.css) - Can't center absolute position (Tailwind.css) 使用CSS隐藏HTML元素(不包含ID或类) - Hide HTML element with CSS (not with ID or Class) Selenium-标识没有ID或CSS类名称的HTML元素 - Selenium - Identifying an HTML element without an ID or CSS class name 使用“data-*”属性替换 HTML 标签中的“id”属性用于 CSS 选择目的 - Using "data-*" attributes to replace the "id" attributes in HTML tags for CSS-Selecting Purpose CSS div样式-我应该使用class还是id? - CSS div style - should I use class or id? 每当我使用顺风 css 添加新的 class 时,我是否必须重新构建我的 css 文件 - Do i have to re-build my css files whenever i add a new class using tailwind css 在 html/css/javascript 中使用 for 循环创建 element_id-value - create the element_id-value using for loop in html/css/javascript 在html元素的ID中插入点或句点的目的是什么 - what is the purpose of inserting a dot or a period in the id of an html element
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM