像表格一样对齐 HTML5 定义列表,无需设置宽度,也无需 Javascript

Ale*_*nch 5 html css semantic-markup

HTML5 DL 元素(类似标记):

<dl class="inline">
    <dt>Name</dt>
    <dd>Alex</dd>
    <dt>Age</dt>
    <dd>22</dd>
    <dt>Hobby</dt>
    <dd>Programming</dd>
</dl>
Run Code Online (Sandbox Code Playgroud)

默认渲染如下:

Name
    Alex
Age
    22
Hobby
    Programming
Run Code Online (Sandbox Code Playgroud)

不过,我希望它像表格一样呈现,其中各列对齐:

Name    Alex
Age     22
Hobby   Programming
Run Code Online (Sandbox Code Playgroud)

这可以使用 css 轻松完成

dl.inline dt{clear:left}
dl.inline dt,dl.inline dd{float:left}
Run Code Online (Sandbox Code Playgroud)

并通过设置 DT 元素的宽度

dl.inline dt{width: 100px}

     100px
<----------->
Name         Alex
Age          22
Hobby        Programming
Run Code Online (Sandbox Code Playgroud)

成功!

问题是,这需要将宽度设置为最长的文本。这意味着 css 依赖于 html。基本上每次我创建一个新的定义列表时,我都必须创建一个新的 css 类,找到最长的单词,然后将其添加到 css 中

dl.inline.dt-where-the-longest-string-is-email-address{width:86px}
Run Code Online (Sandbox Code Playgroud)

我希望 DT 元素自动与最长的元素一样长。

使用 jquery 可以轻松完成此操作。我们基本上会循环 DT 并记住最长的。然后将该 DL 中的所有其他内容设置为该长度:

(function()
{
    // for every DL on the page, that has class 'inline'
    $('dl.inline').each(function(dl_idx, dl_node)
    {
        var dl = $(dl_node),  // the current DL
            longest = 0;   // the current longest

        // go through its DT elements
        dl.each(function(dt_idx, dt_node)
        {
            var width = $(dt_node).width();

            // if this width is larger than the largest so far
            if(width > longest)
            {
                // store this width as the new longest
                longest = width;
            }
        });

        // Set all the DT elements in this DL to the longest found
        dl.children('dt').width(longest);
    });
}());
Run Code Online (Sandbox Code Playgroud)

这段代码可能并不完美,但它阐明了要点。

我希望有一个纯 css 解决方案,它使用浏览器本机代码而不是 javascript。

HTML 表使用类似的属性,display:table-cell尽管我无法让任何东西发挥作用......

我正在寻找的解决方案:

  • 更改DL 标记
  • 使用JavaScript

如果事实证明这样的解决方案是不可能的。或者要求标记不同,那么我想 javascript 解决方案现在就必须要做。

我可能应该指出,我不只是使用表格的原因是因为我觉得数据不够表格化。这种数据更像是表的一行。我觉得定义列表更好地定义了键和值之间的关系(即名称 -> Alex)

Nav*_*eth 1

纯 CSS 解决方案:
查看我在 codepen上的示例