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:

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

I am having trouble viewing an image on my screen

I am trying to add an icon to the left side of my "Skriv ut" text, but unfortunately it is not displaying correctly. This is how I want it to look: https://i.stack.imgur.com/6jcne.png Here is the code snippet I am using: <div class="col-md-4 col-md-o ...

What is preventing the element from being positioned at the bottom of the container?

I have a vertical bar chart with 5 different colored sub-containers. I'm trying to position the 'chicken' sub-container at the bottom of the bar without any bottom-margin, but so far my attempts have been unsuccessful. When I try using absol ...

Align a component vertically in a FlexBox using Material UI

I have a React app where I created a card with specified min width and height, containing only a header. I want to add flexbox that occupies the entire left space with justify-content="center" and align-items="center". This way, when I insert a circular pr ...

Can a shape similar to an inverted circle be created using CSS and jQuery?

I'm stumped on how to create an inverted circle in the corners. I've included a picture for reference. https://i.stack.imgur.com/jeNdh.jpg Is it feasible to achieve this effect using CSS3 or maybe jQuery? ...

Unable to display background image and color on Internet Explorer

The background beneath the slider and footer appears normal in most browsers, but there seems to be an issue with Internet Explorer. Check it out at this link: Do you have any suggestions on how to fix this? ...

What is the best way to execute a function in JavaScript and have it return the output as an image

I have created a special function that selects the image source based on a given criterion: function facilityImg(arr, x) { switch (arr[x]) { case 'Yes': return "Images/checked.png"; case 'No': ...

retrieve all the table data cells except for the initial one

I have a specific table structure that I need to work with: <table> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td&g ...

Concealing a form after submission using JavaScript

After submitting the form, I am attempting to hide it and display a loading GIF. I've experimented with various methods, including changing ClassName to Id, but haven't had success. This is for a school project, and I've spent a significant ...

Splitting your screen in a 10/90 column ratio using React

I am looking to split my screen into a 10/90 ratio of the total screen space. // Here is what I have attempted: return ( <> <div class="row"> <div className="col-md-4" > ; <div class="le ...

Implementing modifications to all HTML elements simultaneously

In my HTML document, there are around 80 small boxes arranged in a grid layout. Each box contains unique text but follows the same structure with three values: name, email, and mobile number. I need to switch the positions of the email and mobile number v ...

The AppBar is consuming space and obstructing other elements on the

As I dive into React/Material-UI and learn the ropes of CSS, I've come across a challenge with my simple page layout featuring an AppBar. Unfortunately, this AppBar is overlapping the elements that should be positioned below it. In my quest for a sol ...

Hiding content in HTML with the Display:none property

After exploring various posts on this topic, I am still unable to find a solution that fits my specific scenario. Despite the challenges, I thought it would be worth asking for recommendations. Currently, I have a PowerShell script generating a report in ...

Using percentages for CSS alignment and adjusting element widths

Greetings everyone! I have been struggling to align two divs - one on the right with a width of 30% and the other on the left with 70%. Despite my efforts, I have not been able to find a solution. I am hopeful that someone here can assist me. My setup inv ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

Is it possible to extract my current location from one website and then access another website based on that location?

I am currently experimenting with an HTML5 script that loads a globe requiring users to click on it to determine the location. Once a location is clicked, another site opens displaying a map of the chosen location. Here is an example of the site with the i ...

XMLWorker: unable to align cell vertically properly

Upon reviewing this code snippet: <table> <tr> <td border="1"> <table> <tr><td>Blah</td></tr> <tr><td>Blah</td></tr> ...

Which web browser(s) can properly display the CSS property display: run-in?

Compatibility with IE7 and FF2.0 Suitable for IE8 and Opera 9+ Works only on IE7 Optimized for IE8 and FF3.5 Supports IE7 and Safari This question came up in a quiz, but I don't have all the browsers to test it. Any assistance would be greatly apprec ...

Switch button while moving cursor

I'm struggling with getting this 2048x512 image, which has 4 stages of transition, to work properly. While I know how to switch it to the final stage on hover, I can't seem to figure out how to incorporate a transition effect. Can someone help? ...

Embedding an Iframe in the Main URL

I have a specific request where I've inserted an anchor tag within an IFRAME. Currently, when the anchor link is clicked, the page redirects within the IFRAME. However, I need the functionality to redirect to the main URL instead of staying within the ...

Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply ...