理解 focus-within 伪类

By 刘志军 , 2021-05-26, 分类: css

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>

focus-within.gif

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

github-foucs-within

如何实现呢?

很简单,不需要js代码,核心css代码就是将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>

github-foucs-within2

是不是很简单


关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

猜你喜欢

2021-05-20
CSS 媒体查询
2021-05-20
CSS元素遮挡问题与z-index属性
2020-04-15
重学前端:相对定位VS绝对定位VS固定定位
2019-05-08
CSS块级元素与行内元素
2021-06-01
理解CSS行高line-height
2021-06-12
理解border-box