CSS3 - animate text align left/center/right

扶醉桌前 提交于 2019-12-01 22:22:02

问题


I've got one line (not wrapped) text inside full width div.

Is it possible to animate this element text alignment so text moves to given side/center - I know I could mensure width and use relative/absolute positioning, but I dont find it straight solution and it also may cause some responsive issues?

Here is demo without animations yet.


回答1:


I needed something similar today. I wanted a button that started with text aligned to the right, but then animated the text to center on hover/focus.

Here is what I came up with. The problem I have with several of the answers I have found is that they animate "position", which is not very performant. I wanted to use only "transform". This is a lot of markup just for centering button text, but seems to work well.

body {margin: 0}
ul, li {
  margin: 0;
  padding: 0;
}
li {
  width: 30%;
  padding: 10px 0;
}
button {
  width: 100%;
  height: 50px;
  margin: 0;
}
.center-line {
  position: absolute;
  width: 2px;
  height: 100%;
  background: lightgray;
  left: 15%;
  top: 0;
}

.outer {
  text-align: right;
  transition: 200ms transform;
}
.inner {
  display: inline-block;
  transition: 200ms transform;
}

button:hover .outer {
  transform: translateX(-50%);
}
button:hover .inner {
  transform: translateX(50%);
}
<ul>
  <li>
    <button>
      <div class="outer">
        <div class="inner">Text 1</div>
      </div>
    </button>
   </li>
  <li>
    <button>
      <div class="outer">
        <div class="inner">Text Two</div>
      </div>
    </button>
   </li>
  <li>
    <button>
      <div class="outer">
        <div class="inner">Text Longer Three</div>
      </div>
    </button>
   </li>
</ul>
<span class="center-line" />



回答2:


text-align property is not animatable, so you can't use it with css transition nor with jquery animate .. Your best shot would be the positioning (use percentage units to retain responsivity).

Hope this helps ...




回答3:


Maybe javascript created marquee would help you out here? <marque> tag is not best way but maybe js marquee would suit you. Marquee (with optional start/stop buttons)

Update: As I understand that marquee would not be best for your needs I came out with another solution using margin-left and changing its value.

Value for right button would depend on how long text you would have there but you can always check that width elements width and adjust in code. I have updated the fiddle with that change in mind: final Fiddle



来源:https://stackoverflow.com/questions/22923524/css3-animate-text-align-left-center-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!