What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario:

https://i.stack.imgur.com/we05U.png

In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in the picture.

If the span were to fit on just one line, this could have been easily achieved using flexbox. However, given the line break seen in the image, applying flex properties to the container causes all lines to reposition themselves sideways to accommodate the new child, which is not the desired outcome.

If handling this layout purely through CSS proves impossible, is there a way to determine the width of the last line of text? One potential solution might involve calculating the width using JavaScript; I simply need a means to identify how much space has already been utilized within that line.

Update: The intended second element will be an input. This requirement rules out utilizing 'text-align: justify' for alignment purposes.

Below is the provided code snippet:

div {border: 1px dotted black; width: 400px}
<div>
  <span>lorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis</span>
  <input >
</div>

Answer №1

For those looking to implement this functionality in JavaScript, you can use the following code snippet assuming that the second child element has an ID of second:

var secondElement = document.getElementById('second');
var parentWidth = secondElement.parentElement.offsetWidth;
secondElement.style.width = parentWidth - secondElement.offsetLeft + 'px';

This approach dynamically calculates the width by subtracting the left offset of the second element from its parent's width.

function computeWidth() {
  var secondElement = document.getElementById('second');
  var parentWidth = secondElement.parentElement.offsetWidth;
  secondElement.style.width = (parentWidth - secondElement.offsetLeft - 5) + 'px';
}

document.querySelector('button').onclick = computeWidth;
div {border: 1px dotted black; width: 500px}
<div>
  <span>lorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam</span>
  <input id="second" />
</div>
<button>Compute width</button>

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'm having trouble removing records from MySql

I am facing an issue with two tables in my database. Table a is referencing table b, or so I believe. Whenever I attempt to delete the entire package using the following query: $query="DELETE a, b FROM classified as a, $sql_table as b WHERE a.ad_id = &ap ...

Filter JSON data deeply for specific values

I am attempting to filter JSON data based on user checkbox selections in JavaScript. The challenge I'm facing is implementing multi-level filtering. The data has two dimensions that need to be filtered: first by OS selection and then by a selected que ...

The Splitter remains inactive until a peculiar series of actions is taken

Trying to troubleshoot this issue with a library called Split.js, which can be found here: https://github.com/nathancahill/Split.js I've encountered an interesting problem where I have to disable the height CSS property of my container, move the spli ...

React Native: error - unhandled action to navigate with payload detected by the navigator

Having trouble navigating from the login screen to the profile screen after email and password authentication. All other functions are working fine - I can retrieve and store the token from the auth API. However, when trying to navigate to the next screen, ...

How come certain rectangles vanish when one rectangle completely fills the space?

Currently, I am encountering an issue with CSS paint worklet and I am trying to determine if it's a browser bug or an error on my end. In the worklet, I am drawing multiple rectangles. Strangely, when one rectangle covers the entire area, the others s ...

Iterate endlessly over CSS styles in Angular 4

I'm looking to create a website background 'screensaver' by looping through an array of background URLs with a delay between switches. Currently, I have the array stored in my .ts file and I am using the NgFor directive in my HTML. However, ...

Placing a div within a 960 grid system can sometimes result in unexpected spacing

Testing on various browsers: Chrome, IE, Firefox. I'm facing an issue where the BusinessNav ID keeps getting pushed over 3 columns. Desired page layout can be found here I could definitely hack this code to adjust the positioning. However, with so m ...

Switching the background color in a diagonal transition when hovering from the bottom left to the top right

I found a helpful answer on this question regarding a certain technique. However, I am curious if it is feasible to implement a diagonal left-to-right background color transition - specifically from bottom-left to top-right? Here is the CSS and HTML code ...

Enhance JSON nesting with knockoutJS

I am currently working on updating a JSON object in memory using the knockout.js user interface. However, I have encountered an issue where changes made in the UI do not seem to reflect on the JSON data itself. To troubleshoot this problem, I have added bu ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Awesome method of redirecting outdated URLs to the most recent established URL

My website heavily relies on JavaScript and communicates with a .NET C# RPC service. We encountered an issue where clients' browsers cached the JavaScript, so we decided to add a version number to the URL in order to force them to use the latest JavaS ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

Turn off hover effect for MUI DataGrid

I'm having trouble figuring out how to disable the hover effect on a row in the MUI Datagrid. I've searched through the API documentation but couldn't find a straightforward solution. Any suggestions on how to achieve this? <DataGrid ...

jQuery: use the "data-target" attribute to toggle the display of a single content area

My code generally works, but there is an issue. When clicking on "Link 1" followed by "Link 2", only the content for Link 2 should be visible. How can I achieve this with my code? $("li").click(function() { $($(this).data("target")).toggle(); // ...

Issues with sending data through ajax using the post method persist on shared web hosting

I'm facing an issue with Ajax post data. It works fine on localhost but not on shared hosting. Here is my code: <script type="text/javascript> $(document).ready(function(){ $("#login").click(function(){ alert(& ...

Implementing an onclick function to execute a search operation

Utilizing PHP, I am dynamically populating a dropdown submenu with rows from a database. If the user wishes to edit a specific record listed in the menu, I want to enable them to do so without requiring any additional clicks. My goal is to accomplish this ...

How to achieve padding of strings in JavaScript or jQuery

Does anyone have information on a similar function in jQuery or JavaScript that mimics the prototype toPaddedString method? ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

Determine line-height and adjust positions using JavaScript in the Chrome browser

I am creating a basic text reading application with a line to aid in easy reading. The functionality involves using the up and down arrow keys on the keyboard to adjust the position of a red line based on the line-height property. This is accomplished thr ...

Delete with Express Router

I have created a basic "Grocery List" web application using the MERN stack (Mongo, Express, React, Node). However, I am facing an issue where my DELETE REST command does not execute unless I refresh the page. Here is the code for my event handler and the b ...