首页 > 解决方案 > CSS - 使居中的文本看起来像打字机

问题描述

我正在尝试制作一个居中的单行文本,使其字母一个接一个地出现,并在其右侧有一个光标。我在下面使用此代码,但它有一些我无法解决的问题:

1)文字虽然我使用text-align: center但一开始没有居中但在左边然后去中心

2)文本最初不是出现在一行上,而是出现在多行上。

.header {
  background-color: black;
  padding: 2%;
  text-align: center;
}
.test {
  color: white;
  overflow: hidden;
  font-size:25px;
  border-right:2px solid #7CDD26;
  animation-delay: 2s;
  animation-duration: 12s;
  animation-fill-mode: both;
  animation-name: spin1;
}
@-webkit-keyframes spin1 {
  0% {width:0px;border-right:0px;}
  1% {width:0px;border-right:2px solid #7CDD26;}
  99% {width:400px;border-right:2px solid #7CDD26;}
}
<div class="header">
  <div class="test">This is a test.</div>
</div>

标签: csscss-animations

解决方案


对于 (a) - 由于您将width属性设置为块级元素 ( div),因此您需要边距以auto使元素居中。text-align属性使容器内的文本居中,而不是容器本身。

至于 (b) - 你已经设置了overflow属性,但是由于你没有设置height,初始值为auto.

所以你的代码可以调整为:

.header {
  background-color: black;
  padding: 2%;
  text-align: center;
}
.test {
  color: white;
  overflow: hidden;
  font-size:25px;
  border-right:2px solid #7CDD26;
  animation-delay: 2s;
  animation-duration: 12s;
  animation-fill-mode: both;
  animation-name: spin1;
margin: auto;
height: 25px;
}
@-webkit-keyframes spin1 { 
  from {width:0px;border-right:0px;}
  to {width:400px;border-right:2px solid #7CDD26;}
}
<div class="header">
  <div class="test">This is a test.</div>
</div>

希望有帮助!


推荐阅读