width restriction to only accommodate on two lines

Whether my text is short or long, I always want to ensure that it remains within two lines by defining the width of my div.

Short Text

+-------------------------+
| Short text goes here |
| Short text goes here |
+-------------------------+

Long Text

+----------------------------------------------+
| Long text goes here long text goes here long |
| text goes here long text goes here long text |
+----------------------------------------------+

Therefore, regardless of the length of the text, I aim to keep it within two lines in terms of width. Is there a way to achieve this using CSS, or would jQuery be a better option?

Answer №1

Custom JavaScript Demo

CSS:

.double-lines {
    background-color: yellow;
    display: inline-block;
    white-space: nowrap;
}
.double-lines.wrapped {
    white-space: normal;
}

JS:

$(".double-lines").each(function () {
    var $width = $(this).width();
    $(this).width($width / 2)
           .addClass("wrapped");
});

Edit: This is a more precise method

Upgraded JavaScript Demo

$(".double-lines").each(function () {
    var $lines = $(this).height() / parseInt($(this).css("lineHeight"));

    while (($lines > 2) || ($(this)[0].scrollWidth > $(this).width())) {
        $(this).width("+=1");
        $lines = $(this).height() / parseInt($(this).css("lineHeight"));
    }
});

Answer №2

Instead of using a single tag, you can achieve the desired result by making some modifications to the source code:

<div>
    <p>long text goes here long text goes here long text goes #</p>
    <p>long text goes here long text goes here long text goes</p>
</div>

<style>
    div > p {
        white-space:nowrap;
    }
</style>

This approach will ensure that both lines remain on one line without setting a specific width for your div element.

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

Order of callback execution in jQuery's ready function

When two JavaScript functions on a page need to be called once the document load is complete, is there a possibility that one function could be executed before the other, or will it always be the same order? For example, using jQuery with the following co ...

Bootstrap icon issue: square displaying instead of the intended icon

I am currently in the process of creating a responsive website using Bootstrap 3. I have successfully downloaded and imported Bootstrap 3 into the root directory of my website. However, I have encountered an issue where the icon does not display correctly ...

Updating the jQuery $ function to accommodate outdated codebases

After using stackoverflow as a valuable resource for years, I decided to join. I have a good grasp on JavaScript and noticed some questions that I could provide input on. As I delved into the platform, I realized the prevalence of jQuery. This prompted me ...

Are there any alternatives to PHP for implementing an auto-complete search feature?

I have decided to focus on using HTML, MySQL, JavaScript, and jQuery for my project. Though I understand that learning PHP would be beneficial in the long run, I don't have enough time to master it all within a week. As for the server-side, I will be ...

Is a pop-up alert necessary for table modifications?

In my user Badges and Achievements table, the default value for a Badge is set to locked. Once a user unlocks a badge, the field value is changed to unlocked. I am looking for a way to notify the user through a popup message when they unlock a new achiev ...

The malfunction of CSS3 effect

I designed a website and used DIV CSS to call an image. .header_bottom_area { background: url(../img/HomepagePanels.jpg)no-repeat scroll center center; max-width: 100%; width: auto; height: 911px; } I would like to have the same image as shown in ...

Why does jQuery function properly in jsfiddle, but not in an HTML file?

I have been troubleshooting repeatedly, but I am unable to figure out why the jQuery code is not functioning as expected. Strangely enough, it works perfectly in jsfiddle! Here is the HTML code: <!doctype html> <html> <head> <meta ch ...

What is the best way to iterate through multiple iframes?

I need help figuring out how to load one iframe while having the next one in line to be displayed. Is there a way to create a script that cycles through multiple iframes after a certain amount of time? ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

The issue with the material design checkbox change functionality not functioning as expected

Currently, I am attempting to dynamically set the state of checkboxes to either true or false. The following code snippet demonstrates what I have tried so far: for(var i = 0; i < bookmakers.length; i++) { $('#' + bookmakers[i].id + &apos ...

Is there a way to position the logo icons on the right side of the footer?

My goal is to connect social media platforms with their respective logos, and I'm encountering an issue. The problem arises when attempting to align the list items to the right of the footer. <footer> <div class="footer-wrapper"> ...

Searching for hidden elements within a div using a filter option

An accordion is located inside a div and a search box has been added to the div with the intention of serving as a search filter. Some accordion elements are visible within the div while others are hidden. The problem arises when trying to make the filter ...

The height of the navigation bar adjusts to fit the image

I'm currently struggling with my html and css learning project. The height of the navigation bar is not adjusting properly to the size of the image. I have tried various solutions, but nothing seems to work. Any guidance would be appreciated! htm ...

Using CSS to create a triangular background within a <div> element

I am looking to create a CSS triangle shape for a background, but I am unsure of how to achieve this or if it is even possible. Ultimately, I want the menu to resemble the image linked below: While I have come across methods to create the desired shape, ...

Creating an HTML structure that limits each li to only contain three div elements can be achieved using React and Underscore.js

To achieve this specific layout, I am looking to utilize only underscore.js functions. Below is the array that I have: var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': &ap ...

A problem arises when trying to showcase the content in a responsive manner on the hamburger menu, particularly when viewing on mobile

As a newcomer to web development, I decided to challenge myself by building an E-Commerce website to enhance my skills. To ensure mobile responsiveness, I opted for a hamburger menu to hide the navbar content. However, despite resizing working flawlessly, ...

Modify the animation on Material UI Autocomplete with an underline effect

In my project, I am utilizing a Material UI Autocomplete component for the "Faculdade" field. Nonetheless, I have observed that the animation/transition effect when this component is focused involves spreading from the middle outwards. I desire the animati ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Executing a 'WebMethod' using jQuery in ASP.NET WebForms

I've placed a breakpoint inside the WebMethod below, but it never seems to get hit. cs: [WebMethod] public static string search() { return "worked"; } aspx: function search() { $.ajax({ type: "POST", url: "ProcessAudit/re ...

Unable to store data in database using Ajax PHP MySQL

Here is the code from my index.php file: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <form name="form1" method='POST'> <sele ...