入坑前端: 理解 focus-within 伪类

python之禅

共 4008字,需浏览 9分钟

 · 2021-05-29

大家好,我是刘志军

这是第3篇关于前端的文章,其实草稿箱的存货还有几十篇,后面慢慢完善,希望最后能整理形成一个完整的前端入坑指南。


目前我感觉我的前端水平,css样式这块基本上能独立实现我想要的东西了。内心不再抗拒也不再恐惧,真好。


focus-within是css中的一个伪类,与 focus 类似,说到focus-within,你一定会想它与focus有什么区别?

focus 表示一个元素获得焦点, 你可以对该元素进行操作。而 focus-within 是表示一个元素或者它的子元素获取焦点时,你可以对该元素进行的操作。

例如,当输入框元素获取焦点时,父元素form可以使用focus-within伪类设置边框属性。

<html>

    <head>
        <style>

            form{
                width: 300px;
                margin: 20px auto;
                background-color: #ccc;
            }

            form:focus-within{
                border: 2px solid blue;
            }
        </style>
    </head>

    <body>

        <form>
            <label>name</label>
            <input type="text" name="name">
            <br>
            <label>age</label>
            <input type="text" name="age">
        </form>

    </body>
</html>

再来看个例子,github的搜索框,当输入框获取焦点时,你会发现整个框会被拉长,这里就应用到了focus-within 伪类。

如何实现呢?

很简单,不需要写任何js代码,核心样式代码就是将input的宽度设置成100%,与父容器等宽,当子元素input获得了焦点时,通过父容器.search的伪类focus-within让宽度拉长就好了。

<html>

<head>
    <style>
        .container {
            margin: 20px auto;
            max-width: 1200px;
            background-color: #24292e;
            padding: 1em;
        }

        .search {
            max-width: 200px;
        }

        .search:focus-within {
            max-width: 470px;
        }

        input {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="search">
            <input type="text">
        </div>
    </div>
</body>

</html>

效果图:

是不是很简单?

推荐阅读:

入坑前端:CSS元素遮挡问题与z-index
入坑前端:一文搞懂 Flex 布局

浏览 52
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报