The problem is to style the detail html element when the focus pseudo-class is trigger.
The
:focus
CSS pseudo-class represents an element (such as a form input) that has received focus. It is generally triggered when the user clicks or taps on an element or selects it with the keyboard’s Tab key.
Here is a demo snippet:
:focus { outline: none; }
body {
display: flex;
flex-direction: column;
gap: 2em;
}
details {
background: red;
}
summary {
background: green;
}
details:hover {
box-shadow:0 0 0 2px blue;
}
/* this one doesn not work */
details:focus {
box-shadow:0 0 0 2px blue;
}
button:focus {
box-shadow:0 0 0 2px blue;
}
<input type="text" value="press tab to switch focus">
<details>
<summary>summary should be blue on focus</summary>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi, ex facilis iusto. Ab laboriosam deserunt neque fuga reprehenderit, inventore non? Quo sint iusto commodi architecto magni sit maiores beatae exercitationem.
</p>
</details>
<button>the button should be blue on focus</button>
2
Answers
After playing a bit with
tabIndex
as suggested by Sebsemillia, I went for another solution. In the origianl snippet we have this structure:Without
tabIndex=0
, the browser focus oninput
, then skipdetails
because it is not an interactive element, then move on to summary, then reachbutton
.With
tabIndex=0
, the browser focus oninput
, then is forced todetails
even it is not an interactive element, then move on to summary, then reachbutton
.Now here is the real problem with my question. Why bother give focus to details? Well the question's title is not good because what OP wants is to wrap the whole
details/summary
with a blue border.here how to actually fix the code.
Replace
with
MDN
Focus does just work out of the box with interactive elements (e.g. inputs, buttons, links,..).
If you want to make another element focusable, you can add the tabindex attribute.
In your case it would look like that: