Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 in this case. If it works with :active, how come it doesn't work with :focus?

Any ideas why?

(Note. I want the DIV's border to turn solid, NOT the textareas)

div.box
{
    width: 300px;
    height: 300px;
    border: thin dashed black;
}

div.box:focus{
    border: thin solid black;
}

<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
371 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}
<p>The outer box border changes when the textarea gets focus.</p>
<div class="box">
    <textarea rows="10" cols="25"></textarea>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...