Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I shift focus to a div through CSS alone?

Tags:

html

css

Is there a way to shift focus to a div by default through pure CSS, and not using JavaScript?

like image 536
ZX12R Avatar asked Mar 31 '10 06:03

ZX12R


People also ask

Can I focus on a div CSS?

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.

How do you focus an element in CSS?

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.

How do you set focus on a specific element in HTML?

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.


4 Answers

No, there isn't.

In normal circumstances, a div can't receive the focus at all, and CSS lacks anything to set the focus.

like image 57
Quentin Avatar answered Nov 15 '22 10:11

Quentin


No CSS does not offer anything on focus. I know you said no JavaScript, but how easy:

document.getElementById('exampleId').focus();
like image 22
Dustin Laine Avatar answered Nov 15 '22 10:11

Dustin Laine


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.

like image 26
Skeets Avatar answered Nov 15 '22 12:11

Skeets


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.

like image 40
JP de la Torre Avatar answered Nov 15 '22 10:11

JP de la Torre