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

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

Adjustable Size with jQuery UI - Resizing Multiple Divs Causes Movement of Adjacent Divs

I've been experimenting with a webpage that consists of a div element containing multiple nested divs and jQuery UI resizable functionality. Essentially, it's a dashboard comprised of individual widgets. My goal is to resize each widget independe ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

Animate in Angular using transform without requiring absolute positioning after the animation is completed

Attempting to incorporate some fancy animations into my project, but running into layout issues when using position: absolute for the animation with transform. export function SlideLeft() { return trigger('slideLeft', [ state('void&a ...

Is it possible to make a div resize to fit its container?

I have a square block measuring 100*100px. The container block it is within can be resized. I need the inner block to adjust its size dynamically so that it always fits inside the parent container without overflow and maintains its square shape. Important ...

How to make a Kendo Grid Combobox template or editor automatically set focus and select all text

I've been experimenting with using the combobox as either an editor or template for a column. The key difference is that one (the template) is always visible, while the other (the editor) is only displayed when the user edits a cell in the column. I&a ...

Positioning a designated div directly above a designated spot on the canvas

I'm grappling with a challenge in my game where the canvas handles most of the animation, but the timer for the game resides outside the canvas in a separate div. I've been struggling to center the timer around the same focal point as the squares ...

NodeJS async/await not pausing for the completion of the previous request's response

function fetchData(input) { return new Promise((resolve, reject) => { $.post({ url: baseURL, data: input }).done(function (response) { resolve({ statusCode: 200, responseData: response }); ...

Creating impenetrable div elements with JavaScript or jQuery

I'm currently working on creating solid blocks using DIVs positioned side by side both horizontally and vertically. I've successfully achieved this when the divs have equal heights. However, an issue arises when a div has larger dimensions; it en ...

Is the background image viewport centered?

I am embarking on a new venture with a website design that is unfamiliar to me, but I have a clear goal in mind... My design concept involves a single large image measuring 1000px x 1000px as the background, while the actual content fills up only 500px x ...

The jQuery function for AJAX does not properly validate the boolean value provided by the controller

I have a controller action that returns a boolean result to jQuery. [HttpGet] public ActionResult IsVoucherValid(string voucherCode) { bool result = false; var voucher = new VoucherCode(voucherCode); if(voucher.Status==0) ...

jQuery doesn't seem to function properly upon initial click

Working with Rails and attempting to implement an ajax bookmark icon functionality. When clicking for the first time, the request is sent but the image does not change; however, subsequent clicks work as expected (request sent and image changes). This is ...

Text in a class button that is not skewed

I crafted a button for my website using a CSS class, aiming for a parallelogram shape by utilizing the skew function. The code worked like a charm, giving the button the desired shape. However, I encountered a dilemma where the text inside the button also ...

What could be causing my tabs to shift to the vertical side when using large, larger, and wide screens?

In my previous research, I came across a question similar to mine: Pure CSS accordion not working within CSS tabs. The solution mentioned works perfectly on monitors of any size, but the difference lies in the use of the a element. In their code, setting t ...

Transferring information between pages through ajax communication

I am working with two pages named testing.php and submission.php. My goal is to send data from testing.php to be displayed on submission.php. For example, when a user clicks on test1, they should be directed to submission.php where I want to display the te ...

What is the reason behind this occurrence with just one 's'?

I'm currently encountering an issue with my HTML form field. Here is the code snippet: <div style="width:100px; padding-top:10px;margin-left:10px;float:left;" align="left">Your Username:</div> <div style="width:300px;float:left;" align ...

AngularJS Material Design sticky header MD table container

I am looking to create a table container to display records with a unique requirement - when the table reaches the top of the screen, its header should stick in place. Can you provide guidance on how to implement this feature? For reference, please check ...

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

Using the $.ajax or $.get function can only retrieve data from local files

Is there a way to use $.ajax or $.get to fetch responses from an XML file located on a remote server? I've noticed that these functions only seem to work with local files. I am currently developing my websites on a local server with a host address lik ...

Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from th ...