Chinyi
Chinyi

Reputation: 3

CSS: How to center texts with transitioning position?

I created 2 inner spans to hold the current and additional contents to be shown on button hover, the transition between initial and hover states works fine, but I have no idea how to center texts both vertically and horizontally?!

.btn {
  background: #C5D200;
  color: #fff;
  width: 150px;
  height: 30px;
  padding: 10px 20px;
  border-radius: 20px;
  display: block;
	position: relative;
	overflow: hidden;
	text-align: center;
}

.content {
	position: absolute;
	transition: top .4s;
}

.top { top: 0; }

.btn:hover .top { top: -50px; }

.bottom { top: 50px; }

.btn:hover .bottom { top: 0; }
<div>
  <a href="#" class="btn">
    <span class="top content">Buy Now</span>
    <span class="bottom content"> On Sale $1</span>
  </a>
</div>

Upvotes: 0

Views: 54

Answers (3)

AHJeebon
AHJeebon

Reputation: 1248

Simply adjust left and top properties.

.btn {
  background: #C5D200;
  color: #fff;
  width: 150px;
  height: 30px;
  padding: 10px 20px;
  border-radius: 20px;
  display: block;
  position: relative;
  overflow: hidden;
  text-align: center;
}
.content{
  position: absolute;
  transition: top .4s;
  top: 15px;
  left: 60px;
}

.bottom           {top: 500px;}
.btn:hover .top   {top: -500px;}
.btn:hover .bottom{top: 15px;}
<div>
  <a href="#" class="btn">
    <span class="top content">Buy Now</span>
    <span class="bottom content"> On Sale $1</span>
  </a>
</div>

Upvotes: 0

James Burgess
James Burgess

Reputation: 497

Try centering with a flex box,

.btn{
    display: flex;
    align-items: centre;
    justify-content: center;
}

Upvotes: 0

Alien
Alien

Reputation: 3678

.btn {
  background: #C5D200;
  color: #fff;
  width: 150px;
  height: 30px;
  padding: 10px 20px;
  border-radius: 20px;
  display: block;
	position: relative;
	overflow: hidden;
	text-align: center;
}

.content {
	position: absolute;
	transition: top .4s;

    /*add this*/
    height: 50px;
    line-height: 50px;
    width: 190px;
    text-align: center;
    left: 0px;


}

.top { top: 0; }

.btn:hover .top { top: -50px; }

.bottom { top: 50px; }

.btn:hover .bottom { top: 0; }
<div>
  <a href="#" class="btn">
    <span class="top content">Buy Now</span>
    <span class="bottom content"> On Sale $1</span>
  </a>
</div>

Upvotes: 2

Related Questions