Search code examples
htmlcsstextposition

CSS: how to relate the position of a div to the last word position of a h4 element


I need to set the position of a div at the end of a h4 text element. If h4 is on a single line then I succeed. But the problem is when the text goes beyond two lines, because my div goes to the end of the first line's width, instead of the last word on the second line.

Is it possible to relate the position of a div to the position of the last word of an h4 element? (So ​​if it goes on two lines it always goes close to the last word)

In the attached image I try to explain it better: I have to do the solution "B".how to set div position to last word


Solution

  • You need to make it with js, only css wont make it.

    // Function to add span on last word
    function spanLastWord(element)
    {
        var pieces = element.innerHTML.split(" ");
        var last = pieces.pop();
        var first = pieces.join(" ");
        element.innerHTML = first + '<span id=\"lastWord\"> ' + last + '</span>';
    }
    
    // Function to position element
    function positionElement(){
      // Get title
      var lastwordContainer =  document.getElementById("lastwordContainer");
      spanLastWord(lastwordContainer);
    
      // Get last word
      var lastWord =  document.getElementById("lastWord");
    
      // Get last word position
      var rect = lastWord.getBoundingClientRect();
      //console.log(rect.top, rect.right, rect.bottom, rect.left);
    
      // Get the div to position
      var divLastWord =  document.getElementById("divLastWord");
      divLastWord.style.top = rect.bottom - 10 + 'px';
      divLastWord.style.left = rect.right - 80 + 'px';
    }
    // event listener to position in cas of resize
    window.addEventListener('resize', function(event) {
    
      positionElement();
    
    }, true);
    
    positionElement();
    #divLastWord{
      border: 2px solid yellow;
      position: absolute;
    }
    <h4 id="lastwordContainer" class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut odio arcu. Aenean augue massa, placerat fermentum consectetur sit amet, pulvinar nec mi. Mauris velit tellus, posuere nec cursus ut, mattis ut orci. Maecenas tincidunt tellus quis orci finibus tristique. Suspendisse tristique augue ultrices leo tristique ultrices. Vestibulum semper lacinia pulvinar. Pellentesque dignissim nunc in vulputate bibendum. Praesent risus nibh, suscipit ac blandit a, rhoncus vel sem. Cras interdum fermentum augue eget pellentesque. Integer velit massa, cursus in volutpat cursus, iaculis ac elit. In quis ex dui. Ut a tellus erat. Nam fermentum id elit eu tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras a ultricies arcu, et hendrerit nunc. Pellentesque vitae dignissim arcu, ut aliquam nibh.</h4>
    <div id="divLastWord">I am on the last word</div>