skip to Main Content

Considering code below:

.switch {
  display: flex;
  appearance: none;
  border: none;
  background-color: white;
  align-items: center;
}

.switch::before {
  height: 45px;
  border-radius: 200px;
  background-color: blue;
  display: flex;
  align-items: center;
  padding: 0px 50px 0px 2px;
  content: "•";
  color: white;
  font-size: 100px;
}
<button class="switch" type="submit">
  &nbsp; Can edit users
</button>

It might not be obvious, but the toggle (white dot) is not vertically-aligned inside its container (blue box). It seems link to baseline; but I dunno how to fix it.

It there a way to make this toggle perfectly vertical-aligned without creating another div?
Or, is there another way to make it works without creating another div?
Thanks.

2

Answers


  1. Since you use content: "•";, the position of the dot will depend on the font you are using. Therefore, I offer the following solution:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    .switch {
      --height: 46px;
      --width: 94px;
      --offset: 6px;
      display: inline-flex;
      align-items: center;
      appearance: none;
      border: 0;
      background: none;
      position: relative;
      cursor: pointer;
    }
    
    .switch:before {
      content: '';
      width: var(--width);
      height: var(--height);
      border-radius: calc( 2 * var(--width) );
      flex: none;
      background-color: blue;
    }
    
    .switch:after {
      content: '';
      position: absolute;
      top: var(--offset);
      left: var(--offset);
      width: calc( var(--height) - 2 * var(--offset) );
      aspect-ratio: 1;
      /* or */
      /* height: calc( var(--height) - 2 * var(--offset) ); */
      background-color: white;
      border-radius: 50%;
      transition: transform .4s;
      will-change: transform;
    }
    
    .switch.active:after {
      transform: translateX( calc( var(--width) - var(--height) ) );
    }
    <button class="switch" type="button" onclick="this.classList.toggle('active')">
      &nbsp; Can edit users
    </button>
    Login or Signup to reply.
  2. Build it with a radial-gradient and you can easily control the position/size like you want:

    .switch {
      display: flex;
      appearance: none;
      border: none;
      background-color: white;
      align-items: center;
    }
    
    .switch::before {
      --r: 15px; /* radius */
      --g: 5px; /* gap */
    
      content:"";
      height: calc(2*(var(--r) + var(--g)));
      aspect-ratio: 2;
      border-radius: 200px;
      background: 
        radial-gradient(var(--r) at calc(var(--r) + var(--g)) 50%,
        #fff 90%,blue); /* colors here */
      padding: var(--g);
      box-sizing: border-box;
      margin-right: 10px;
    }
    <button class="switch" type="submit">
      Can edit users
    </button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search