多行缩进HTML标记

Mol*_*ine 6 html html5 coding-style indentation

我找不到有关如何在多行上缩进HTML标记的指南,而我当前使用的解决方案并不能真正满足我的要求。

假设我们有一个非常长的div声明,例如:

<div data-something data-something-else data-is-html="true" class="html-class another-html-class yet-another-html-class a-class-that-makes-this-declaration-extremely-long" id="just-a-regular-id">
Run Code Online (Sandbox Code Playgroud)

为了避免在找到这些大线条时水平滚动,我通常采用以下方式缩进它们:

<div 
    data-something 
    data-something-else 
    data-is-html="true" 
    class="html-class another-html-class yet-another-html-class a-class-that-makes-
    this-declaration-extremely-long" 
    id="just-a-regular-id"
>
    <p>Some element inside the DIV</p>
</div>
Run Code Online (Sandbox Code Playgroud)

在可读性方面,我认为效果很好,但我对此有些担忧。

  • 这样认为是一种好习惯吗?
  • 您会发现可读性更高,可以>使开头的HTML Tag中的结尾处与最后一个元素保持内联,或者像上例中那样与新行保持一行吗?
  • 您还有其他首选方法来处理极长的HTML声明吗?

如果您知道一些涵盖这种特殊情况的HTML样式指南,那么请随意分享,因为我没有在网上找到任何特定的东西。

sha*_*ell 8

在谷歌的HTML / CSS样式指南建议包皮过长的线路时,显著提高了可读性,并提供三种技术,其中的每一个包括关闭>与属性的最后一行:

  1. 将长行分成可接受长度的多行:
<div class="my-class" id="my-id" data-a="my value for data attribute a"
    data-b="my value for data attribute b" data-c="my value for data attribute c">
    The content of my div.
</div>
Run Code Online (Sandbox Code Playgroud)
  1. 通过将每个属性放在自己的缩进行上来打破长行:
<div
    class="my-class"
    id="my-id"
    data-a="my value for data attribute a"
    data-b="my value for data attribute b"
    data-c="my value for data attribute c">
    The content of my div.
</div>
Run Code Online (Sandbox Code Playgroud)
  1. 与#2 类似,除了第一个属性在首行,后续属性缩进以匹配第一个属性:
<element-with-long-name class="my-class"
                        id="my-id"
                        data-a="my value for data attribute a"
                        data-b="my value for data attribute b"
                        data-c="my value for data attribute c">
</element-with-long-name>
Run Code Online (Sandbox Code Playgroud)

在我看来,当元素包含内容时,#3 不会提高可读性。


小智 3

就我个人而言,我发现这是一个很好的做法,并且我发现使用多行更具可读性。我对我制作的网站使用相同的约定。在我的大学里,我们学到了同样的惯例,它明确指出:

避免长代码行

使用HTML编辑器时,左右滚动阅读HTML代码很不方便。尽量避免代码行超过 80 个字符。

公约的其余部分可以在这里找到: https://www.w3schools.com/html/html5_syntax.asp