skip to Main Content

I have a grid of buttons and on hover/focus I want to display a outline around the button. The problem is the other buttons are covering the element’s outline. How do I make the outline display on top of the other buttons? I’d prefer to not use pseudo elements.

.grid {
  display: grid;
  margin: 1rem;
  grid-template-columns: repeat(2, 1fr);
  grid-auto-rows: 1fr;
  width: 12rem;
  place-items: stretch;
  aspect-ratio: 1;
} 

.tile:where(:hover, :focus, :focus-visible, :focus-within) {
  outline: 5px solid blue;
}
<div class="grid">
  <button class="tile">1</button>
  <button class="tile">2</button>
  <button class="tile">3</button>
  <button class="tile">4</button>
</div>

3

Answers


  1. Please try setting z-index to the .tile:where(:hover, :focus, :focus-visible, :focus-within) to selector just like below.

    .tile:where(:hover, :focus, :focus-visible, :focus-within) {
      outline: 5px solid blue;
      z-index: 1;
    }
    

    Working example is below:

    .grid {
      display: grid;
      margin: 1rem;
      grid-template-columns: repeat(2, 1fr);
      grid-auto-rows: 1fr;
      width: 12rem;
      place-items: stretch;
      aspect-ratio: 1;
    } 
    
    .tile:where(:hover, :focus, :focus-visible, :focus-within) {
      outline: 5px solid blue;
      z-index: 1;
    }
    <div class="grid">
      <button class="tile">1</button>
      <button class="tile">2</button>
      <button class="tile">3</button>
      <button class="tile">4</button>
    </div>
    Login or Signup to reply.
  2. User a z-index on your ...:hover... {...} (etc.) rule. Value 1 is enough for the isolated example below, but you might have to set it to a higher value in more complex situations.

    .grid {
      display: grid;
      margin: 1rem;
      grid-template-columns: repeat(2, 1fr);
      grid-auto-rows: 1fr;
      width: 12rem;
      place-items: stretch;
      aspect-ratio: 1;
    } 
    
    .tile:where(:hover, :focus, :focus-visible, :focus-within) {
      outline: 5px solid blue;
      z-index: 1;
    }
    <div class="grid">
      <button class="tile">1</button>
      <button class="tile">2</button>
      <button class="tile">3</button>
      <button class="tile">4</button>
    </div>
    Login or Signup to reply.
  3. Use "border" property.

    .tile:where(:hover, :focus, :focus-visible, :focus-within) { border: 5px solid blue; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search