Using CSS to align the position of a div with the last word position of an h4 element

Trying to figure out how to position a div at the end of an h4 text element has been challenging. When the h4 text is on a single line, it's easy to place the div correctly. However, things get complicated when the text spans multiple lines. In that case, the div ends up at the width of the first line instead of next to the last word on the second line.

Is there a way to align the position of the div with the last word of the h4 element? This way, even if the text wraps onto two lines, the div will always be close to the last word.

I've attached an image to better illustrate what I'm trying to achieve: I need to implement solution "B." Here's the link to the image for reference: https://i.sstatic.net/uZNpi.png

Answer №1

In order to achieve this effect, JavaScript is necessary as CSS alone will not suffice.

// Custom function to insert span around last word
function wrapLastWord(element)
{
    var words = element.innerHTML.split(" ");
    var lastWord = words.pop();
    var theRest = words.join(" ");
    element.innerHTML = theRest + '<span id=\"lastWord\"> ' + lastWord + '</span>';
}

// Function to position the element
function positionElement(){
  // Get container element
  var lastwordContainer = document.getElementById("lastwordContainer");
  wrapLastWord(lastwordContainer);

  // Get the last word 
  var lastWord = document.getElementById("lastWord");

  // Get position of the last word
  var rect = lastWord.getBoundingClientRect();

  // Calculate position for the div 
  var divLastWord = document.getElementById("divLastWord");
  divLastWord.style.top = rect.bottom - 10 + 'px';
  divLastWord.style.left = rect.right - 80 + 'px';
}
// Add event listener for dynamic positioning on window 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing PHP Code with an External JavaScript File in an HTML Document

I have a script called initialize_database.js that utilizes JQuery to trigger a PHP script for creating a database and some tables. I made sure the PHP script is working correctly by adding HTML to test it independently, and it performed as expected. Below ...

What is the meaning of this CSS acronym?

div[id^=picture]:target{ /*applying various styles here*/ } I stumbled upon the snippet of code shown above on a website discussing CSS image galleries. Can anyone clarify what this code accomplishes? Appreciate it. ...

adjust the size of a form field to match the background image dimensions

I'm encountering an issue while trying to solve this particular challenge: My goal is to integrate a login box onto a full-screen image. Although I've come across numerous methods for incorporating an image into a form field, my task requires me ...

Leveraging MUI v5 sx Prop for Applying Various CSS Properties Simultaneously (such as margin, border-radius, and more)

Is there a more efficient way to write the following code that utilizes the sx prop's access to spacing units? <MUIComponent sx={{ borderRadius: '4px 8px 12px 16px' }} /> Could it be written like this instead? <MUIComponent sx={{ b ...

Every time I adjust the browser height on my landing page, the elements start to overlap each other

Something strange is happening - as I shorten the height of the browser, elements on the page start to overlap. I've tried using Firebug to troubleshoot, but haven't had any luck so far. Maybe someone here can help me out! EDIT: It seems that e ...

What is the method for adding a tag within a specific div ID in ExtJS?

I am looking to insert a new tag within existing tags using extjs, based on the div id 'task123', and also trigger an alert message accordingly. Below is the HTML code snippet: <div id="task123"> <div class="msg" id="sample"> ...

What is the most effective method for resetting the scroll position of a browser when refreshing a page?

Portfolio Query I am in the process of setting up a basic portfolio website. My navigation bar includes various links, one of which is labeled "About Me". Upon clicking this link, the page immediately jumps to a specific section with an element ID of #abo ...

Ways to boost an array index in JavaScript

I recently developed a JavaScript function that involves defining an array and then appending the values of that array to an HTML table. However, I am facing an issue with increasing the array index dynamically. <script src="https://cdnjs.cloudflare. ...

What steps can I take to guarantee that a select change event occurs following the setting of ngmodel in Angular2?

I am facing an issue with a select element wherein a basic (change) handler is attached along with an ngmodel. Whenever an <option> with a ng value is set, the change handler triggers before the [(ngModel)] reflects the new values. <div> ...

Is there a way to extract just the src attribute from an Image tag using PHP?

Similar Question: How can I extract img src, title and alt using php? <img width="200" height="300" src="http://runapvo.apivo.com/files/2011/06/2444-200x300.jpg" class="attachment-medium" alt="2444" title="2444" /> Given the image tag abov ...

Output each uploaded file using jQuery's console.log function

My AJAX upload form is set up and working, but when multiple files are selected they all upload at once. I want to create a separate div for each file to show the progress individually. However, when I try to test the number of files using this code snippe ...

My Django function doesn't get triggered by the form submission using post method

I'm facing a frustrating dilemma and issue. Currently, I am working on a form written in HTML using Django, which is meant to update information in my database related to the specific page it is on. The problem lies in the fact that the Django termi ...

The CSS styling is not being rendered correctly on the AngularJS HTML page

Encountering a puzzling situation here. Our angular controller is successfully delivering data to the page, but we are facing an issue with rendering a table due to an unknown number of columns: <table border="1" ng-repeat="table in xc.tables"> ...

Which slider was featured in the unity3d.com/5 website?

While browsing the internet, I came across the website and was intrigued by the slider effect featured in the "graphics" section. I am eager to figure out how to replicate that stunning visual effect. ...

Incorporating a closing screen into a game built with Canvas and jQuery

After following a tutorial on creating a snake game, I decided to work on enhancing it as a side project. Currently, the game has a start screen where players can begin the game by pressing "start." My goal is to implement an end screen that displays the ...

Ways to implement a 'Delete' feature in a PHP audio tag player

"I successfully retrieved the name of the uploaded file and am able to play it in my browser. How can I incorporate a delete function for each user-uploaded song?" echo "<hr />"; echo "<h4>" . $name . "<br /><a href='#' titl ...

Guide on submitting a multi-step form using jQuery

Greetings, I am in need of assistance with submitting a jQuery step wizard form. Although I have a plugin that helps, it primarily uses jQuery rather than HTML. So far, I have accomplished the following steps: - Set up the necessary database and table - C ...

What methods can I use to toggle between different divs using navigation buttons?

There are 4 divs on my webpage that I need to toggle between using the up and down arrows. Despite trying an if else statement, it doesn't work as intended. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.c ...

Tips for positioning your side navigation menu parallel to the page edge

Im looking to have the side navigation floated to the left as I scroll down the page. I tried using the sticky property, but it didn't work out. Here's a snippet of the code: .sticky-class { position: sticky; top: 30px; } This is how my HTML ...

Responsive Bootstrap 4 Login Form with customized top height

This login form was created using Bootstrap 4, starting with a preset that I then customized to fit my needs. As someone new to Bootstrap and CSS, I struggled with making the form responsive. When resizing the window, the top portion gets cut off and is no ...