使用CSS突出显示活动表单?

Bil*_*kil 4 html css forms focus

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <style>
            form:focus{
                background:red;
            }
        </style>
        <title>Home, sweet home</title>
    </head>
    <body>
        <form>
            <input type="text"/>
            <input type="submit"/>
        </form>
        <form>
            <input type="text"/>
            <input type="submit"/>
        </form>
        <form>
            <input type="text"/>
            <input type="submit"/>
        </form>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,这也是我提出这个问题的原因.如果作为焦点突出显示,我怎样才能获得具有一个的表单?也就是说,我希望能够将样式应用于活动的FORM,而不是活动的INPUT - 没有JS或其他东西可行吗?

小智 7

这是一个较老的问题,但截至目前,一些比较流行的浏览器支持一个名为css伪选择器:focus-within,它可以设置一个具有焦点输入的表单(没有javascript).

以下是对选择器的当前支持:http://caniuse.com/#search=focus-within

如果您使用的是支持的浏览器,请举例说明:https://codepen.io/jumprope-design/pen/LjxORX


o.v*_*.v. 3

这段代码可以作为练习但可能不是您应该使用的解决方案。依赖的版本legend实际上似乎可以接受。

没有form:focus选择器,所以我认为个人input:focus可以使用伪元素创建所需的效果。但是,伪元素只能用在具有 content 的元素上,就像我要替换input[type=submit]button

form {
    position:relative;
}
/*style the pseudo-element before a button that is a general sibling
  of any element that currently has focus within a form*/
form *:focus~button:before{
    content:"";display:block;background:red;
    /*take up the entire space of the form*/
    position:absolute;top:0;right:0;bottom:0;left:0;
    /*but render behind its children*/
    z-index:-1;
}
Run Code Online (Sandbox Code Playgroud)

摆弄了一下,但它立即看起来非常疯狂,所以我重构了解决方案以依赖于legendelement。享受 :)