Home > Blockchain >  Can focus-within exclude certain elements?
Can focus-within exclude certain elements?

Time:09-18

I've got a stepper component like this

stepper component no focus

Note the DOM is something like

<div >
   <button>-</button>
   <input type='number' />
   <button> </button>
</div>

I was using .my-stepper:focus-within to ensure that the whole stepper looks focused when you're in the the input

stepper component focus on container only

But I don't like that when you focus a button, you end up with a doubled up focus

enter image description here

I was hoping to use something like .my-stepper:focus-within:not(button:focus) to ensure that if the focus is on the input, container should look focused, but if focus is on a button, the container should NOT look focused.

stepper component button focus, no focus on cotainer

How can I get the effect I'm looking for without changing my DOM?

CodePudding user response:

:has() should give you what you want. Though keep in mind the browser support isn't 100% currently. But I think this falls nicely under progressive enhancement.

MDN

.my-stepper:focus-within {
  outline: 1;
}

.my-stepper:has(button:focus) {
  outline: 0;
}

CodePudding user response:

consider extracting your buttons outside of container. This will let you focus within stepper only:

.box {
position: relative;
width: 100px;
}
.btn-layer {
top:0;
position: absolute;
}
.minus {
left: 0;
}
.plus {
right: 0
}

input {
width: 20px;
}
<div >
  <div >
     <input type='number' />
  </div>
  <div >
         <button >-</button>
         <button > </button>
  </div>
</div>

  • Related