Home > Blockchain >  How to ensure that a div is always centered when another one disappears after an animation?
How to ensure that a div is always centered when another one disappears after an animation?

Time:09-11

(enter image description here

The problem is I make this transition happen with the following code:

.button:not(.disabled):hover .icon {
  transform: translate3d(150%, 0, 0);
}

The 150% is just an arbitrary value, if you go inside App.js and change the width of the icon (line 10), you can tell that it's no longer centered. I can't wrap my head around a solution that would ensure the following (my goals):

  • When the button is not hovered, both the icon and the text should be center.
  • When the button is hovered, only the icon should be ultimately centered.

Would appreciate any guidance.

CodePudding user response:

First give your button a fixed width.

.button {
  width: 130px;
}

and then you just need to set the position of your icon class to absolute on button hover.

.button:not(.disabled):hover .icon {
  position: absolute;
}

CodePudding user response:

The below solution only works when the <Button> has fixed-width:

button {
  --trans: .3s ease-out;
  
  font-size: 20px;
  width: 250px;
  height: 50px;
  padding: .1em .5em;
  background: none;
  border: 2px solid black;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  
  display: flex;
  align-items: center;
  justify-content: center;
  gap: .5em;
    
  transition: var(--trans);
}

button > i {
  font-size: 30px;
  color: #444;
  transition: var(--trans);
}

button:hover > i {
  font-size: 40px;
  color: crimson;
}

button span {
  max-width: 100%;
  overflow: visible;
  white-space: nowrap;
  transition: var(--trans);
}

button:hover {
  gap: 0;
}

button:hover span {
  opacity: 0;
  max-width: 0;
  transform: translatex(20cqb);
}
<button>
  <i>♥️</i>
  <span>Button Label</span>
</button>

  •  Tags:  
  • css
  • Related