Is there a way to shift focus to a div by default through pure CSS, and not using JavaScript?
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. Note that a <div> can get focus if you set the contenteditable="true" attribute.
The :focus selector is used to select the element that has focus. Tip: The :focus selector is allowed on elements that accept keyboard events or other user inputs.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
No, there isn't.
In normal circumstances, a div can't receive the focus at all, and CSS lacks anything to set the focus.
No CSS does not offer anything on focus. I know you said no JavaScript, but how easy:
document.getElementById('exampleId').focus();
Since none of the answers here worked for me (although I wanted focus on an input, not a div) I'll post one that does work:
autofocus
just like this:
<input autofocus>
Of course, the OP is asking for how to make this work with a div, which this doesn't. As was previously mentioned, contenteditable="yes" will make the div focusable, but this unfortunately doesn't work either:
<div contenteditable="yes" autofocus>
This doesn't work!!
</div>
In my opinion, this is kind of an oversight in HTML5, this div should act like an input field. However, for the time being, it seems that javascript is required for this to happen.
Any element can receive focus if it is contenteditable. However, CSS doesn't recognize :focus pseudoclasses for elements other than input, select, a, textarea and button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With