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
As per the spec:
The
:focus
pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).
The <div>
does not accept input, so it cannot have :focus
. Furthermore, CSS does not allow you to set styles on an element based on targeting its descendants. So you can't really do this unless you are willing to use JavaScript.
While this can't be achieved with CSS/HTML alone, it can be achieved with JavaScript (without need of a library):
var textareas = document.getElementsByTagName('textarea');
for (i=0;i<textareas.length;i++){
// you can omit the 'if' if you want to style the parent node regardless of its
// element type
if (textareas[i].parentNode.tagName.toString().toLowerCase() == 'div') {
textareas[i].onfocus = function(){
this.parentNode.style.borderStyle = 'solid';
}
textareas[i].onblur = function(){
this.parentNode.style.borderStyle = 'dashed';
}
}
}
JS Fiddle demo.
Incidentally, with a library, such as jQuery, the above could be condensed down to:
$('textarea').focus(
function(){
$(this).parent('div').css('border-style','solid');
}).blur(
function(){
$(this).parent('div').css('border-style','dashed');
});
JS Fiddle demo.
References:
DIV
elements can get focus if set the tabindex
attribute. Here is the working example.
#focus-example > .extra {
display: none;
}
#focus-example:focus > .extra {
display: block;
}
<div id="focus-example" tabindex="0">
<div>Focus me!</div>
<div class="extra">Hooray!</div>
</div>
For more information about focus
and blur
, you can check out this article.
Update:
And here is another example using focus
to create a menu
.
#toggleMenu:focus {
outline: none;
}
button:focus + .menu {
display: block;
}
.menu {
display: none;
}
.menu:focus {
display: none;
}
<div id="toggleMenu" tabindex="0">
<button type="button">Menu</button>
<ul class="menu" tabindex="1">
<li>Home</li>
<li>About Me</li>
<li>Contacts</li>
</ul>
</div>
Some people, like me, will benefit from using the :focus-within
pseudo-class.
Using it will apply the css you want to a div, for instance.
You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within