display: table-column 有什么作用?

What does display: table-column do?

根据mdndisplay: table-column应该

behave like HTML elements.

但据我所知,<col> 元素没有显示模式,它们实际上只是 html 的粗略边缘,它定义了标记中的样式。那么 css 中的 table-column 究竟应该做什么呢?

虽然你是对的,但他们只是为该列中的每个 tdth 定义了样式,他们自己在技术上确实有一个 display 模式,因为它是 display: table-column 赋予他们这种能力。

如果将 <col> 设置为 display: none,相应的 table 元素不再应用在 col 中设置的样式(在这个 Fiddle).

就个人而言,我觉得允许 HTML 元素表现得像一组 CSS 规则来指示 table 的样式有点老套内容。

它允许您将其他 HTML 元素视为 <col> 元素

因为 <col> 元素不属于任何内容类别并且它们不允许包含任何内容,所以它们基本上从流中删除并且它们的内容被忽略(就像它们有 display: none ).

display: none 不同,当正确应用于列组的子项时,table-column 关键字可用于影响与该组中的列关联的单元格(甚至模拟单元格)的样式.

根据CSS 2.1 §17.2 The CSS table model

Elements with display set to table-column or table-column-group are not rendered (exactly as if they had display: none), but they are useful, because they may have attributes which induce a certain style for the columns they represent.

根据CSS 2.1 §17.3 Columns

Table cells may belong to two contexts: rows and columns. However, in the source document cells are descendants of rows, never of columns. Nevertheless, some aspects of cells can be influenced by setting properties on columns.

The following properties apply to column and column-group elements: [border, background, width, visibility]

例如:

.table {
    display: table;
    table-layout: fixed;
    border-collapse: collapse;
    width: 100%;
}
.table-row {
    display: table-row;
}
.table-cell {
    display: table-cell;
    border: 1px solid silver;
    padding: 0.5em;
}
.table-colgroup {
    display: table-column-group;
}
.table-col {
    display: table-column;
}
.col-1 {
    /* Invalid. See: CSS 2.1 §17.3 Columns */
    text-align: center;
}
.col-2 {
    /* Valid.   See: CSS 2.1 §17.3 Columns */
    background-color: tomato;   
}
<div class="table">
    <div class="table-colgroup">
        <div class="table-col col-1">Col 1 (hidden content)</div>
        <div class="table-col col-2">Col 2 (hidden content)</div>
    </div>
    <div class="table-row">
        <div class="table-cell">Row 1, Col 1</div>
        <div class="table-cell">Row 1, Col 2 </div>
    </div>
    <div class="table-row">
        <div class="table-cell">Row 2, Col 1</div>
        <div class="table-cell">Row 2, Col 2</div>
    </div>
    <div class="table-row">
        <div class="table-cell">Row 3, Col 1</div>
        <div class="table-cell">Row 3, Col 2</div>
    </div>
</div>


无障碍问题

尽管存在 table-* 显示属性,但对 table 使用非语义 HTML 不利于可访问性,因为它可能会导致屏幕阅读器等辅助技术产生误解数据。

根据 Web Accessibility Initiative (WAI) Tables Tutorial:

Data tables are used to organize data with a logical relationship in grids. Accessible tables need HTML markup that indicates header cells and data cells and defines their relationship. Assistive technologies use this information to provide context to users.

如果您想使用非语义标记和 CSS 构建一个 table,我建议您阅读 Tables, CSS Display Properties, and ARIA | Adrian Roselli