54

快速了解CSS新出的列选择符双管道(||)

 5 years ago
source link: https://www.zhangxinxu.com/wordpress/2019/02/css-column-combinator/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

byzhangxinxu from https://www.zhangxinxu.com/wordpress/?p=8475

本文可全文转载,个人网站无需授权,只要保留原作者、出处以及文中链接即可,任何网站均可摘要聚合,商用请联系授权。

了解列选择符

示例用法:

col.selected || td {
    background-color: skyblue;
}

平时我们用过空格, > , +~ ,现在出来个双管道 || ,是不是没见过,这个双管道 || 就是本文要介绍的列选择符。

列选择符是规范中刚出现不久的新选择符,目前浏览器的兼容性还不足以实际项目中应用,因此本文仅简单介绍下,让大家知道大致是干什么用的。

在Table布局和Grid布局中都有列的概念,有时候我们希望控制整列的样式。有两种方法,一种是借助 :nth-col() 或者 :nth-last-col() 伪类,不过这两个伪类目前浏览器尚未支持;还有一种是借助原生Table布局中的 <colgroup><col> 元素实现,这个兼容性非常好。

我们通过一个简单例子快速了解下这两个元素,如下表格HTML代码:

<table border="1" width="600">
    <colgroup>
        <col>
        <col span="2" class="ancestor">
        <col span="2" class="brother">
    </colgroup>
    <tr>
        <td> </td>
        <th scope="col">后代选择符</th>
        <th scope="col">子选择符</th>
        <th scope="col">相邻兄弟选择符</th>
        <th scope="col">随后兄弟选择符</th>
    </tr>
    <tr>
        <th scope="row">示例</th>
        <td>.foo .bar {}</td>
        <td>.foo > .bar {}</td>
        <td>.foo + .bar {}</td>
        <td>.foo ~ .bar {}</td>
    </tr>
</table>

可以看出表格共有5列。其中, <colgroup> 元素中有3个 <col> 元素,从 span 属性值可以看出,这3个 <col> 元素分别占据1列,2列和2列。此时,我们给后面2个 <col> 元素设置背景色,就可以看到背景色作用在整列上了,CSS如下:

.ancestor {
    background-color: dodgerblue;
}
.brother {
    background-color: skyblue;
}

最终效果如下图:

JBnyauV.png!web

但是,有时候,我们的单元格并不是正好属于某一列,而是跨列,此时, <col> 元素是会忽略这些跨列元素的。举个例子:

<table border="1" width="200">
    <colgroup>
        <col span="2">
        <col class="selected">
    </colgroup>
    <tbody>
        <tr>
            <td>A</td>
            <td>B</td>
            <td>C</td>
        </tr>
        <tr>
            <td colspan="2">D</td>
            <td>E</td>
        </tr>
        <tr>
            <td>F</td>
            <td colspan="2">G</td>
        </tr>
    </tbody>
</table>
col.selected {
    background-color: skyblue;
}

此时仅C和E两个单元格有天蓝色的背景色,G单元格虽然也覆盖了第3列,由于同时也属于第2列,于是被无视了,效果如下图:

FnUBRnQ.png!web

这就有问题了,很多时候,我们就是要G单元格也有背景色的,只要包含该列,都认为是目标对象。为了应对这种需求,列选择符应运而生了。

列选择符写作双管道 || ,是两个字符,和JavaScript语言中的逻辑或写法一致,但是,在CSS中却不是“或”的意思,用“属于”解释要更恰当。

通过如下CSS选择器,可以让G单元格也有背景色:

col.selected || td {
    background-color: skyblue;
}

col.selected || td 意思就是选择所有属于 col.selected<td> 元素,哪怕这个 <td> 元素横跨多列。

于是,我们可以看到如下图所示的效果:

YZBRbqA.png!web

本文内容就这些,结束!

jmI77vn.png!web

本文为原创文章,会经常更新知识点以及修正一些错误,因此转载请保留原出处,方便溯源,避免陈旧错误知识的误导,同时有更好的阅读体验。

本文地址: https://www.zhangxinxu.com/wordpress/?p=8475

(本篇完)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK