使用伪元素添加不定长的下划线 | 8月更文挑战

1,406 阅读1分钟

一种很常见的设计图样式如下图:要求一排“链接”或文字,当某一项处于选中状态或鼠标移动到其上方时,显示为红色,并且底部显示一定长度的下划线。

image.png

值得注意的是,这个下划线与TAB文字的长度并不相关。

在不了解伪元素的情况下,我们很容易得出,对于每一个Tab选项卡,我们需要设置两个元素,上方的TAB文字主体部分,以及下方的定长下划线部分。

<!DOCTYPE html>
<body>
    <div class="tab">
        <div class="tab-main">
            TAB文字内容
        </div>
        <div class="underline"></div>
    </div>
</body>

<style>
    html {
        font-size: 50px;
    }

    .tab {
        width: 10em;
        height: 4em;
        
        position: relative;

        /*为了便于查看调试,我们显示出其边界出来*/
        border: 1px solid red;

        /*以下代码保持TAB居中*/
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .underline {
        /*保持其位置于父DOM底部居中位置*/
        position: absolute;
        bottom: 0;
        left: calc(50% - 1em); 

        width: 2em;
        height: 0.1em;
        background-color: red;

    }
</style>
</html>

其展示样式如下图,为了便于理解,我们保留了完整的边框。

image.png

对于这个常用的设计图,是否有更简单的代码实现呢?有的,借助伪元素。

MDN文档关于伪元素的定义,包括其中常用的伪元素:::before, ::after ,有了官方文档链接,我们不再多说,上代码:

<!DOCTYPE html>
<body>
    <div class="tab">
        <div class="tab-main">
            TAB文字内容
        </div>
    </div>
</body>

<style>
    html {
        font-size: 50px;
    }

    .tab {
        width: 10em;
        height: 4em;
        
        position: relative;

        /*为了便于查看调试,我们显示出其边界出来*/
        border: 1px solid red;

        /*以下代码保持TAB居中*/
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .tab-main::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: calc(50% - 1em);
        width: 2em;
        height: 0.1em;
        background-color: red;
    }
</style>
</html>