2016-09-25 48 views
0

我创建了两个内部跨度来保存当前和额外的内容显示在按钮盘旋上,初始状态和悬停状态之间的转换工作正常,但我不知道如何将文本垂直和水平居中?CSS:如何以过渡位置居中文本?

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

 
.content { 
 
\t position: absolute; 
 
\t 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>

回答

2

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

 
.content { 
 
\t position: absolute; 
 
\t 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>

+0

刚刚获悉这个有用的技巧,它工作得很好,非常感谢! – Chinyi

0

尝试用柔性盒定心,

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

只需调整左右和T op属性。

.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>