skip to Main Content

I have a button group of three buttons. They all have borders and on hover on each one of them I need to change border-color of hovered button.

The problem is that I am not sure how to arrange all of these border without creating a double border.

I came up with the solution below and it works (although buttons are jumping a little bit still) but only in webkit browsers because of the has pseudo-class. If you try to open it in Firefox, you will see that on hover on Main button there will double border between the Main and the First buttons.

So maybe there is another way of doing this that is more cross-browser? Or maybe I can adjust this solution somehow.

Thanks for the help.

.container {
  display: flex;
}

button {
  margin: 0;
  border: 1px solid black;
  display: block;
  font-size: 4rem;
}

.main {
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
}

.main:hover, .first:hover, .last:hover {
  border-color: blue;
}

.main:hover ~ .last {
  border-left: 1px solid transparent;
}

.first:has(~ .main:hover) {
  border-right: 1px solid transparent;
}
<div class="container">
    <button class="first">1</button>
    <button class="main">
        Main button
    </button>
    <button class="last">2</button>
</div>

2

Answers


  1. You can do away with any transparent borders, if you simply make your buttons overlap. Done here by a margin-left: -1px on all but the first button.

    position: relative and on hover, z-index: 1 get added, so that the hovered button is the "top" one.

    .container {
      display: flex;
    }
    
    button {
      position: relative;
      margin: 0;
      border: 1px solid black;
      display: block;
      font-size: 4rem;
    }
    
    button + button {
      margin-left: -1px;
    }
    
    button:hover {
      z-index: 1;
      border-color: blue;
    }
    <div class="container">
      <button class="first">1</button>
      <button class="main">
            Main button
        </button>
      <button class="last">2</button>
    </div>
    Login or Signup to reply.
  2. Considering that your buttons will have background you can do the following:

    .container {
      --b: 2px; /* border thickness */
    
      display: inline-grid;
      grid-auto-flow: column;
      /* the below will define the borders */
      gap: var(--b);
      padding: var(--b);
      background: #000;
    }
    
    button {
      margin: 0;
      font-size: 4rem;
      border: none; /* no border on buttons*/
      background: #f3f3f3;
    }
    
    button:hover {
      outline: var(--b) solid red; /* use an outline on hover */
    }
    <div class="container">
      <button class="first">1</button>
      <button class="main">
            Main button
        </button>
      <button class="last">2</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search