`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this:

<div>Sample text to check how many lines the text is broken into</div>

And the corresponding CSS is:

div {
  width: 100px;
  word-break: break-all;
}

When viewed in the browser, the text will appear as shown in the image below. How can I calculate the number of lines it has broken into from the original text?

Please provide guidance on achieving this.

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

Answer №1

If you want to find out how many lines fit in a container based on its line height, you can use the following code:

function calculateLines($container) {
    var lineHeight = parseFloat(window.getComputedStyle($container[0], null).getPropertyValue("line-height"), 10);
    var containerHeight = $container.height();
    var lines = Math.round(containerHeight / lineHeight);
    return lines;
};

//Simply call the function and provide your container class/selector
var totalLines = calculateLines($('.my-container'));

Answer №2

To determine the accurate line height and identify other styles impacting the overall height, one should examine the offsetHeight of the paragraph. Once you obtain the total height, subtract any CSS-related elements and then divide by the line height.

Please note: I am composing this response on my mobile device and have not conducted any testing.

Answer №3

To implement hyphens at the word break, you can utilize the hyphens CSS property.

Code Snippet:

div {
  max-width: 150px;
  hyphens: auto;
  margin:auto;
}

p {
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}
<div>
  <p>Now in some circumstances, designers may use squares and rectangles to help you visualize what should and could be in a specific location.</p>
</div>

However, this solution may encounter browser support issues.

I came across a useful article discussing the CSS hyphens

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

strategies for chaining together multiple observables with varying data types and operations

Hey everyone! I'm facing a situation where I have a form with multiple select types, and the options for these inputs are coming from an API. I then take the data emitted from the HTTP request observable and feed it into my FormGroup, and everything i ...

Checking the parameters passed to a function in Typescript: A step-by-step guide

Currently, I am working with Typescript and then transpiling my TS code into JavaScript. However, I have encountered an issue that I am struggling to resolve. The error message I am facing is as follows: Error Found in TypeScript on Line:2 - error TS230 ...

Ensure that the dropdown menu remains visible even after the mouse no longer hovers over it

Looking to create a main menu with dropdown items that appear when the user hovers over them? You may have noticed that typically, the dropdown disappears once the hover event is lost. But what if you want the menu to stay visible and only disappear upon c ...

Can AdonisJS 4.1.0 support conditional queries?

I am exploring the capabilities of AdonisJs query builder by referring to their documentation at Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section: const query = Database. ...

Using JavaScript to disable and re-enable an ASP.NET Timer control

I currently have a webpage built with ASP.Net that includes an ASP:Timer control <asp:Timer ID="TimerRefresh" runat="server" Interval="5000" Enabled="true" OnTick="TimerRefresh_Tick"> </asp:Timer> It is connected to an asp:UpdatePanel on the ...

The absence of jasmine-node assertions in promises goes unnoticed

Everything seems to be running smoothly with the code below, except for the assertion part. Whenever I run the test using Jasmine, it reports 0 assertions. Is there a way to include my assertions within promises so they are recognized? it("should open sav ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Expand Menu Options (jQuery)

Currently facing a jQuery problem that I can't seem to figure out. I've set up a menu with submenu elements and want to toggle the content height by clicking on menu items. The issue arises when clicking on another item causes the content to coll ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

Using the Markdown attribute in this context prevents the translate pipe from translating the string

I have a paragraph within an Angular component that includes a markdown attribute. Occasionally, the markdown is causing the translation pipe to not translate the title.description string: <p class="someClass" markdown>{{tile.description | ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

Jhipster - Simplifying Session Authentication with the Power of Jquery

I have completed the following tasks. Developed a Jhipster application with Http Session Authentication Configured Cors settings I am experiencing issues authenticating through Jquery ajax. I keep encountering the error message below. { "timestamp" : ...

Mastering CSS Sprites: A Guide to Aligning Sprite Buttons at the Bottom

In my web app, I have a bottom navigation bar with 9 buttons, each represented by a Sprite Image having 3 different states. The challenge I'm facing is aligning all the images at the bottom of the nav bar or div. The icons vary slightly in size, and ...

What methods can be employed to ensure that the DRF (Django-REST-Framework) Token remains intact and does not disappear with each page refresh?

IMPORTANT: I am utilizing Pure HTML+jQuery+AJAX without Python, Django, or Templates for the front-end development. I have successfully managed to retrieve a User-Based Token from the API Backend, inserted it into the Header File for subsequent requests, ...

Struggling to understand why the PHP/HTML form with a file upload field is not successfully uploading

I've been staring at this code for the past two hours and I can't seem to spot the issue. It's probably something simple, as I keep getting an undefined index error, but it's eluding me. Could you please take a look with fresh eyes? He ...

What can be done to avoid a form being reset when it returns no results?

I've recently created a mysql and php search page, which is working well. However, I noticed that when the form is submitted and there are no results returned, the <option> tags get reset. Is there a way to prevent this from happening? META: I ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

How to Keep Button Highlighted After Clicking

I've experimented with various methods like using :active, :focus, adding a class, and modifying CSS rules through jQuery to maintain the button highlight, but none of them have been successful. Please take a look at my code and point out any mistakes ...

Unlock the Power of TWBS Ratchet: Manually Closing Modal Windows

Currently, I am in the process of developing a mobile web application using Ratchet. The main task at hand involves opening a modal, filling out a form, clicking a button to save the input data, and then closing the modal. Although I have managed to close ...

What causes the element to load with a transparent appearance? And why is my JavaScript code overriding the hover effect on it?

My goal is to have an element fade out when clicked and then fade back in when its space is clicked again. I also want the opacity of the element to be 0.9 instead of 1 when visible. I've encountered two issues with my code. First, the hover selector ...