Using :focus to style outer div?

后端 未结 10 749
礼貌的吻别
礼貌的吻别 2020-12-02 18:24

When I begin writing text in the textarea, I want the outer div, with a class box, to have it\'s border turned solid instead of dashed, but somehow the :focus doesn\'t apply

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 18:34

    Other posters have already explained why the :focus pseudo class is insufficient, but finally there is a CSS-based standard solution.

    CSS Selectors Level 4 defines a new pseudo class:

    :focus-within

    From MDN:

    The :focus-within CSS pseudo-class matches any element that the :focus pseudo-class matches or that has a descendant that the :focus pseudo-class matches. (This includes descendants in shadow trees.)

    So now with the :focus-within pseudo class - styling the outer div when the textarea gets clicked becomes trivial.

    .box:focus-within {
        border: thin solid black;
    }
    

    .box {
        width: 300px;
        height: 300px;
        border: 5px dashed red;
    }
    
    .box:focus-within {
        border: 5px solid green;
    }

    The outer box border changes when the textarea gets focus.

    Codepen demo

    NB: Browser Support : Chrome (60+), Firefox and Safari

提交回复
热议问题