Bryan Dellinger
Bryan Dellinger

Reputation: 5294

centering span after transform

trying to create one of the animated buttons available on semantic ui specifically the animated shopping cart one https://semantic-ui.com/elements/button.html

I created a fiddle here where I did it using css transforms.

https://jsfiddle.net/n37arru2/100/

my question is, is there a way to vertically and horizontally position the span that slides in on hover without having to use top, left css attributes?

span {
  position: absolute;
  top: -45px;
  left: 14px;
  transition: top .6s linear;
}

button {
  position: relative;
  transition: all .6s linear
}

i {
  color: #FFF;
  font-size: 34px !important;
  /* 24px preferred icon size */
  vertical-align: middle;
  transition: transform .6s linear;
}

span {
  position: absolute;
  top: -45px;
  left: 14px;
  transition: top .6s linear;
}

button:hover > i {
  transform: translate3d(0px, 45px, 0px);
}

button:hover > span {
  top: 12px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 
 <button class="btn btn-primary">
   <i class="material-icons">face</i>
   <span>Face</span>
 </button> 

Upvotes: 1

Views: 48

Answers (1)

user7207170
user7207170

Reputation:

Instead of tweaking around the values, you can make use of these:

top: 50%;
left: 50%;
transform:translate(-50%,-50%);

The above is used to center the element having absolute positioning with relation to its parent container. So, initially setting the span to a negative top value and on transition setting to 50% will center it.

span {
  position: absolute;
  top: -50%;
  left: 50%;
  transform:translate(-50%,-50%);
  transition: top .6s linear;
}

button:hover > span {
    top: 50%;
}

button{
  position: relative;
  transition: all .6s linear
}

i {
  color: #FFF;
  font-size: 34px !important; /* 24px preferred icon size */
  vertical-align: middle;
  transition: transform .6s linear;
}

span {
  position: absolute;
  top: -50%;
  left: 50%;
  transform:translate(-50%,-50%);
  transition: top .6s linear;
}

button:hover > i {
    transform: translate3d(0px, 45px, 0px);
}

button:hover > span {
    top: 50%;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 
 <button class="btn btn-primary">
   <i class="material-icons">face</i>
   <span>Face</span>
 </button> 
      

Upvotes: 2

Related Questions