Search code examples
htmlcsstextcolor

Dynamic text colour fill css


I am trying to fill in text with colour from left to right as with the following codepen.

This is causing a problem with the following css:

@keyframes stripes {
    to {
        width: 32px;
    }
}

Words which are longer than 32px, aren't being completely filled in and stop by 32px. If I increase this width, short words (e.g. dog) will be filled in at a fast pace.

I would like to have all words filled-in in 2 seconds (irrespective of the word length)

Anyone has an idea how this can be done please?

Thanks!


Solution

  • .tooltiptext {
        position: relative;
        display: inline-block;
    }
    .tooltiptext:after {
        content: "";
    }
    .popUpWord {
        color: pink;
        white-space: nowrap;
    }
    .popUpWordBlack {
        color: black;
    }
    .outPop {
        margin: auto;
        background: none;
        overflow: hidden;
        display: block;
        position: absolute;
        animation-play-state: unset;
        left: 0;
        top: 0;
        width:0;
    }
    .outPopBlack:hover + .outPop,
    .outPop:hover {
        animation: stripes 2s linear 1 forwards;
    }
    .outPopBlack {
        display: block;
        position: relative;
        z-index: 0;
    }
    @keyframes stripes {
        to {
            width: 100%;
        }
    }
    <span class="tooltiptext"> 
      <span class="outPopBlack">
        <span class="popUpWordBlack">hello World</span>
      </span>  
      <span class="outPop">
        <span class="popUpWord">hello World</span>
      </span>
    </span>

    if you don't have to use multiple lines you can use this method ,

    add "display: inline-block;" to tooltiptext

    add white-space: nowrap; to .popUpWord,

    change style of .outPop to margin: auto; background: none; overflow: hidden; display: block; position: absolute; animation-play-state: unset; left: 0; top: 0; width:0;

    also you can use these method in less code

    .text {
      position: relative;
      display: inline-block;
      z-index: 0;
    }
    
    .text:after {
      content: "HEllo World";
      position: absolute;
      z-index: 1;
      color: red;
      left: 0;
      top: 0;
      width: 0;
      white-space: nowrap;
      overflow: hidden;
      transition: 500ms linear all;
    }
    
    .text:hover:after {
      width: 100%;
    }
    
    .text1 {
      position: relative;
      display: inline-block;
      z-index: 0;
    }
    
    .text1>.dup {
      content: "HEllo World";
      position: absolute;
      z-index: 1;
      color: red;
      left: 0;
      top: 0;
      width: 0;
      white-space: nowrap;
      overflow: hidden;
      transition: 500ms linear all;
    }
    
    .text1:hover>.dup {
      width: 100%;
    }
    <div class="text">
      HEllo World
    </div>
    <br>
    <br>
    <div class="text1">
      HEllo World
      <span class="dup">HEllo World</span>
    </div>