When text exceeds multiple lines, display an ellipsis to indicate overflow and wrap only at word boundaries

Here is an example snippet of my code:

  <div class="container">
    <div class="item n1">Proe Schugaienz</div>
    <div class="item n2">Proe Schugaienz</div>
  </div>

and I am using the following jQuery code:

$('.item').dotdotdot({
  wrap: 'word',
  fallbackToLetter: false
})

along with this CSS:

.item {
  margin: 5px;
  background: red;
  padding: 2px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.n1 {
  width: 8px;
}

.n2 {
  width: 80px;
}

However, the result I currently get is not what I expected:

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

I am aiming for this desired outcome:

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

Is it possible to achieve this with just CSS or do I need to use dotdotdot.js? I want the text to be truncated with ellipsis if it doesn't fit within its parent container, and avoid letter-hyphenation.

I don't want the height of my container to expand (since I have a lot of data), this is just an example and hardcoding blocks is not an option.

https://plnkr.co/edit/IxS0CReJicRfDdeGpoPo?p=preview

Answer №1

Utilize the flex property

<div class="wrapper">
 <p>Lorem Ipsum</p>
 <span>Dolor Sit Amet</span>
</div>
.wrapper {
   display: flex;
   justify-content: center; /* aligns content horizontally */
   align-items: center; /* positions content vertically */
}

Answer №2

Presented here is a suggestion to avoid breaking words - the markup has been modified accordingly:

  1. To prevent word breakage, I have used a flexbox container item for the div inner with dotdotdot applied - ensuring two key things:

    a. inner adjusts its width based on content

    b. Words will not break due to word-wrap: break-word set by dotdotdot

  2. Now we can identify instances where word break or overflow may occur - this happens when the width of inner surpasses that of item.

    This detection can be done within the dotdotdot callback! When words start to break, an ellipsis is needed - replace the text with ... just like dotdotdot does.

Check out the demo below:

$('.inner').dotdotdot({
  wrap: 'word',
  watch: 'window',
  fallbackToLetter: false,
  callback: function(isTruncated) {
    // detecting 'break-word'
    if($(this).outerWidth() > $(this).closest('.item').outerWidth()) {
      $(this).text('...');
    }
  }
});
.item {
  margin: 5px;
  background: red;
  padding: 2px;
  display:flex;
  height: 100px;
}
.n1 {
  width: 12px;
}
.n2 {
  width: 80px;
}
.n3 {
  width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.dotdotdot/1.7.4/jquery.dotdotdot.js"></script>
<div class="container">
  <div class="item n1">
    <div class="inner">Proe Schugaienz.</div>
  </div>
  <div class="item n2">
    <div class="inner">
      Proe Schugaienz. More text here. More text here. More text here.
    </div>
  </div>
    <div class="item n3">
    <div class="inner">
      Proe Schugaienz. More text here. More text here. More text here.
    </div>
  </div>
</div>

Answer №3

To enhance the appearance of the .n1 class, consider setting the display to inline-block and adjusting the line-height to 26px (or a value that you prefer). Additionally, increase the width to 16px to accommodate two letters comfortably. Update your CSS with the following code:

.item {
  margin: 5px;
  background: red;
  padding: 2px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.n1 {
  line-height: 26px;
  width: 16px;
}
.n2 {
  width: 80px;
}

Make sure to eliminate any unnecessary lines in script.js that were previously used to achieve this effect. Following these adjustments should improve the functionality for you.

Answer №4

In my opinion, the simplest fix for this issue is utilizing the CSS property "text-overflow: ellipsis". You can achieve the desired outcome by implementing the following CSS snippet:

.element.e1 {width: 30px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;}

Keep in mind that adjusting the width parameter will determine when the dots appear.

Answer №5

If you have a specific element that you would like to display with a limited width, use the code below:

.example-element{
max-width: your-desired-width;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

You can customize the maximum width according to your needs.

Answer №6

By utilizing JavaScript, here is a method to achieve the desired outcome without relying on any external libraries or plugins.

const items = document.querySelectorAll('.item')
const log = document.querySelector('#log')

const MIN_WIDTH = 32

// Verify if the elements are smaller than the specified MIN_WIDTH 
// and add a class to hide the text while displaying an ellipsis.
for (let item of items) {
  if (item.clientWidth < MIN_WIDTH) {
    item.classList.add('hidden')
  }
}
.item {
  background-color: red;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-bottom: 0.5rem;
  padding: 0.2rem;
}
.n1 {
  width: 1.5rem; // 24px
}
.n2 {
  width: 6rem;
}

/* 
  This CSS will mask the text and exhibit an ellipsis instead
*/
.hidden {
  position: relative;
  white-space: nowrap;
}
.hidden::before {
  content: '...';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: red;
  text-align: center;
}
<div class="container">
  <div class="item n1">Proe Schugaienz</div>
  <div class="item n2">Proe Schugaienz</div>
</div>

If you intend to adjust the size of the elements dynamically, encapsulate the loop in a function for flexibility in execution.

Answer №7

        $.fn.detectOverflow = function () {
            return this.each(function () {
                if ($(this)[0].scrollWidth > $(this).innerWidth()) {
                    $(this).css('overflow', 'hidden').css('text-overflow', 'ellipsis').css('white-space', 'nowrap').css('min-width', '16px');
                }
            });
        };
        $(function () {
            $('.element').detectOverflow();
        });
        .element {
            margin: 5px;
            background: red;
            padding: 2px;
            overflow: auto;
            word-wrap: break-word;
        }

        .n1 {
            width: 8px;
        }

        .n2 {
            width: 80px;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
        <div class="element n1">Proe Schugaienz</div>
        <div class="element n2">Proe Schugaienz</div>
    </div>

Answer №8

By combining text-overflow: ellipsis; with the div's properties, you can achieve ellipsis even without content overflow. For those looking to add ellipsis at the beginning of the content, a technique known as "reverse ellipsis" can be utilized. You don't need any JavaScript code for this and can easily implement it in your projects. Check out this Plnkr I've set up for you:

https://plnkr.co/edit/TwotVdtGMaTi6SWaQcbO?p=preview


.box {
  width: 250px;
  border: 1px solid silver;
  padding: 1em;
  margin: 1em 0;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.reverse-ellipsis {
  /* Implementing reverse ellipsis */
  text-overflow: clip;
  position: relative;
  background-color: #FFF;
}

.reverse-ellipsis:before {
  content: '\02026';
  position: absolute;
  z-index: 1;
  left: -1em;
  background-color: inherit;
  padding-left: 1em;
  margin-left: 0.5em;
}

.reverse-ellipsis span {
  min-width: 100%;
  position: relative;
  display: inline-block;
  float: right;
  overflow: visible;
  background-color: inherit;
  text-indent: 0.5em;
}

.reverse-ellipsis span:before {
  content: '';
  position: absolute;
  display: inline-block;
  width: 1em;
  height: 1em;
  background-color: inherit;
  z-index: 200;
  left: -.5em;
}

body {
  margin: 1em;
}

In the HTML section of the code, an extra element within .reverse-ellipsis (in this case, a span) is added to demonstrate how to include ellipsis at the beginning of the content while still showing the end. Feel free to explore this approach in your own projects!

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

Implementing context menus on the Material-UI DataGrid is a straightforward process that can enhance the user experience

I am looking to enhance my context menus to be more like what is demonstrated here: Currently, I have only been able to achieve something similar to this example: https://codesandbox.io/s/xenodochial-snow-pz1fr?file=/src/DataGridTest.tsx The contextmenu ...

The functionality of the typeof operator is not behaving as anticipated

I am currently working on a script to verify the existence of a specific JavaScript object. var success = function(data) { var x= 0; var numOfCards = data.length; for (x=0;x<data.length - 1;x++) { if (typeof data[x].l ...

Save the altered aircraft shapes as JSON files, utilizing the Three.js framework

I've been working on modifying the vertices of a plane geometry in order to create new shapes. However, I've run into an issue where when I export the modified geometry as JSON, the changes I made to the vertices are not included in the exported ...

No display of Tailwind updates on local server in Safari browser using NextJS and a Mac M1

For my personal project with NextJS, I am using Tailwind CSS, but I am experiencing frequent issues with updating styles. It seems like there is a 50/50 chance that Tailwind will apply the styles to the component properly, and sometimes I have to go throug ...

Capture the JSON data and save it into a separate JSON file

Just starting out with JSON and using an ajax call, I've managed to retrieve a JSON object with the following structure: { data: [ { bouquet: "Interactive", list: [] }, { bouquet: "Movie ...

Calculate the number of parent nodes and their respective child nodes

I am curious about how I can determine the number of children nested within parent-child relationships. For example: const parent = document.querySelectorAll('.parent'); parent.forEach(el => { const ul = el.querySelector('.child3-chi ...

React hooks causing the for loop to only work on the second iteration

I am working on a project where I need to implement tags, similar to what you see on this website. Before adding a tag, I want to ensure that it hasn't already been selected by the user. I have set up a for loop to compare the new tag with the existin ...

Is there a way to customize the scrollbar color based on the user's preference?

Instead of hardcoding the scrollbar color to red, I want to change it based on a color variable provided by the user. I believe there are two possible solutions to this issue: Is it possible to assign a variable to line 15 instead of a specific color lik ...

The inserted button's click event does not trigger the contentEditable DIV

I have a contentEditable DIV that I manage using the directive below: <div class="msg-input-area" [class.focused]="isMsgAreaFocused" contenteditable [contenteditableModel]="msgText" (contenteditableModelChang ...

What could be causing ngInfiniteScroll to not work properly with tables?

I've been attempting to incorporate ngInfiniteScroll into my table using ng-repeat on <tbody> however, it isn't triggering when I reach the end of the page. <div infinite-scroll="list.getMoreItems()"> <table md-table md-row-se ...

I encountered difficulty clicking a button due to its unique button data-order-group-id while using python and selenium

Need help with javascript code for repeating orders: <div class="col-ea-1 repeat-order repeatable-order"> #common row in other snippets <button data-order-group-id="a9755447-04ff-4d00-59bf-06ff87f8ead6" #different row data- ...

Using Django to send AJAX POST requests to pass JavaScript variables for form initialization

Currently, I am engaged in a Django project where I have managed to gather all my variables in JavaScript and now attempting to initialize a form (within a modal popup) on the same page without any need for refresh. The form is successfully displaying insi ...

"Create a Vue element containing a trio of buttons each displaying a distinct numeral

I am currently dealing with a component that generates three items (boxes) each containing three buttons (created using v-for). The issue I am facing is that when I click on a button, all the numbers inside the buttons change simultaneously. I want to be a ...

What are some best practices for utilizing `element.offsetParent` in HTML SVG elements?

I'm currently updating some JavaScript code that relies on the .offsetParent property. The recent changes in the application involve the use of SVG elements, which are causing issues with the JavaScript as mySvgElement.offsetParent always returns unde ...

What repercussions come from failing to implement an event handler for 'data' events in post requests?

If you take a look at the response provided by Casey Chu (posted on Nov30'10) in this particular question: How do you extract POST data in Node.js? You'll find that he is handling 'data' events to assemble the request body. The code sn ...

Identifying the category of a value through a conditional check on another value

I am looking for my code editor to automatically determine the type of extraData based on the value of error, which is being narrowed down by an if statement: export enum ErrorCodes { Unknown = 'UNKWN', BadRequest = 'BDREQ', } int ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

What is the best way to use CSS to connect the tips of shapes for perfect alignment?

In an attempt to utilize CSS3 for creating shapes and aligning them to resemble a certain image, I have successfully crafted a pink square along with 4 gray rectangles. Initially, my approach involved creating separate div elements for each shape and adjus ...

How can I ensure that my content stays fixed at the bottom of a scrolling div in Material UI React?

I have developed a React JS component using Material UI that includes a chat input feature. However, I am facing an issue where the width of the chat input is always half the screen size on desktop or mobile devices. When I try to change the width to 100%, ...

Saving changes made in HTML is not supported when a checkbox is selected and the page is navigated in a React application using Bootstrap

In my array, there are multiple "question" elements with a similar structure like this: <><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div ...