Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow outside of its boundaries. Here's an illustration that depicts the problem:

As illustrated, there are three key obstacles that I aim to overcome:

  • I intend to restrict the text within the confines of the div.
  • I want to ensure that the truncation doesn't occur midway through a word.
  • I would also like to include a "read more" link at the end of the previewed description.

While browsing through various e-commerce platforms, I noticed this feature implemented numerous times. Despite conducting extensive research for hours, I haven't come across a clear-cut solution for implementing this functionality.

Here's the code snippet responsible for generating all the product cards:

for($i = 0; $i<$numberOfItems; $i++) {
    //echo $output_array[$i]["itemName"];
    echo '<a href="/itemDetails.php?itemCode=';echo $output_array[$i]["itemCode"]; echo '&itemName='; echo $output_array[$i]["itemName"];echo'">
    <div id="item" style="background-color: transparent; width:243px;height:auto;float:left; margin-left:20px; margin-top:20px; max-width:800px; display:inline-block;">
    <div id="itemPicture" class="itemImage"; > 
    <div id="price" class="pricetag">
    <div id="priceText" class="priceText";>';
    echo "€".$output_array[$i]["itemPrice"];

    echo '</div></div>';
    $imageSource = "http://www.imagine-app.nl/ProductImages/".$output_array[$i]["firstImage"].".jpg";
    echo '<img src="';echo $imageSource; echo'" style="max-width:100%; border:0px;"> 

    </div>

    <div id="itemName" class="itemName"">';
        echo $output_array[$i]["itemName"];
    echo '</div>'; ?>

    <div id="itemDescription" class="itemDescription" style="height:">
    <?php  echo $output_array[$i]["itemDescription"];
    echo '</div>';
    ?>

    <?php
    echo '<div id="itemComment" class="itemComment"">
          Lees verder! 
    </div>

</div></a>';
}

If anyone has insights on resolving these issues, your assistance would be greatly appreciated. Thank you in advance!

UPDATE

Following suggestions provided, I delved into the concept of "Line Clamping," which involves CSS or Javascript methodologies to achieve the desired outcome. By incorporating both the Javascript code from musically_ut and the CSS approach by Unamata Sanatarai, I was able to make progress:

Efforts have been fruitful thus far as the text no longer spills beyond the div borders. However, two challenges persist:

  • The truncated text sometimes extends below the footer of my product card inexplicably.
  • Occasionally, words get cutoff unnaturally (in Dutch, the missing word should be "beschikt").

Your recommendations and suggestions are welcomed.

PS: The second screenshot reflects the CSS integration since the Javascript implementation only functioned correctly with one product card (possibly due to the dynamic generation via PHP 'for' loop).

Answer №1

If you're looking to clamp multiple lines of text, CSS only allows clamping of the first line. While Webkit/Opera do offer some support for clamping multiple lines, it may not be sufficient for your needs.

There are various workarounds available, including an all-CSS solution detailed in this resource. You can also explore more options in this article: http://css-tricks.com/line-clampin/

For a reliable solution, consider utilizing javascript with tools like Clamp.js to achieve the desired multi-line clamping effect.

Answer №2

Utilizing CSS text-overflow along with Line Clamping:

div {
  display: block; 
  display: -webkit-box;
  width: 200px;
  height: 40px;
  margin: 0 auto;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  padding:20px;
  overflow:hidden;
  text-overflow: ellipsis;
}

Check out the live demo here: http://jsfiddle.net/5Z4Wu/

Answer №3

Take a look at my custom Fiddle:

The script within the fiddle positions the link labeled Know More precisely at the bottom-right corner of a div with limited area and overflow set to hidden, adjusting according to screen size. When Know More is clicked, it toggles the visibility of the overflowing content.

jQuery

/* If id name of div containing text changes, only this script modification is needed */
var txtCont = $('#wrappingText');
/*******************************/
var lines = txtCont.get(0).getClientRects();
txtCont.css('display','inline-block');

jQuery.fn.exists = function(){return this.length>0;}

function debugTxt(txt)
{
    var lineHeight = txtCont.css('line-height').replace("px", '');
    var txtContHeight = txtCont.height();
    txtCont.parent().height(lineHeight*Math.floor(txtContHeight/lineHeight));
    if (txt*lineHeight>txtContHeight){
       if(!txtCont.parent().find('.knowMore').exists()){
       txtCont.parent().append('<div class="knowMore">Know </div>');
    }}
    else
       txtCont.parent().find('.knowMore').remove();
}
debugTxt(lines.length);

$('.knowMore').click(function(){
    $(this).prev().toggleClass("visible");
    $(this).toggleClass('knowLess');
    $(this).parent().toggleClass("parentClick");
});

Appropriate CSS usage is crucial for achieving the correct output. Below is the CSS utilized in the fiddle:

#wrapper{
    position:relative;
}
html,body,#wrapper,#wrappingText{
    margin:0px;
    padding:0px;
    width:100%;
    height:100%;
}
#wrappingText{
    display:inline;
    overflow:hidden;
}
.knowMore{
    position:absolute;
    bottom:0px;
    right:0px;
    background-color:white;
    color:blue;
    cursor:pointer;
}
.knowMore:before{
    content:"...";
}
.knowMore:after{
    content:"More";
}
.knowLess:before{
    content:"";
}
.knowLess:after{
    content:"Less";
}

.visible{
    overflow:visible !important;
}

.parentClick{
    width:auto !important;
    height:auto !important;
}

Updated

<div class="container">
.
.
.
<div class="wrapper">
<div class="wrappingText"></div>
</div>
.
.
.
</div>

The structure above should be followed for the plugin used in the fiddle. You are free to use any class names you prefer. In the given HTML, the div named wrappingText contains the text and must be enclosed within another div. In this case, wrappingText is wrapped within a div with the classname wrapper.

To utilize the plugin, simply call it with the class name of the text-containing div and pass the main parent class name as a parameter:

$('.wrappingText').knowMoreLess('.container'); // CALLING PLUGIN

Additional instructions and details have been included in the comments in the updated fiddle below:

Updated Fiddle

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 am looking to access a public method from a different component in Angular 2

Trying to access the headerExpand property from app.component is causing an error message in the console: metadata_resolver.js:559 Uncaught Error: Invalid providers for "Page1" - only instances of Provider and Type are allowed, got: [?undefined?] page1 ...

React Js month picker problem encountered

I am currently working on implementing a month picker using the library called react-month-picker The code is functioning correctly in React: https://codesandbox.io/s/react-month-picker-forked-84rqr However, when I tried to integrate the same code into a ...

The nth-child selector is not functioning correctly with material-ui components

Trying to figure out how to give two paragraphs different background colors using nth-child. Here's the JSX: <div className={classes.paragraphs}> <p>Test 1</p> <p>Test 2</p> </div> And the CSS: const useSty ...

Determine all subarrays within two integer arrays whose sum matches a specified target number

Given two integer arrays, find all subarrays whose sum equals a specified target number. For example, if array1 = [1,2,3,4] and array2 = [7,3,4], with the sumToFind being 5, the function findSubArrays(array1, array2, num) should output [[1,4],[2,3]]. I in ...

Incorporate a caret into an element using CSS styling

issue I encountered an issue where <textarea> and Javascript had some quirks when trying to transfer the value into a <pre> tag. My aim was to implement a blinking caret in the <pre> as if I were pressing F7. The reason behind not using ...

What is the interaction between Vue's v-model and the update:modelValue directive, and how can we customize the default behavior to prevent it from

Could someone provide an explanation of the usage of v-model with :modelValue and update:modelValue? What happens when both are used together? In the code snippet below, a component is shown: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3. ...

Starting the selection process using AngularJS and ng-repeat

My challenge is to have a pre-filled option in a select-box using ng-repeat with AngularJS 1.1.5. However, the select box always starts off with nothing selected and an empty option, which I don't want. It seems to be a side effect of not having anyth ...

Connecting Documents Together

I'm looking to learn how to link files together, specifically creating a button that when clicked takes you to another site or the next page of reading. I apologize if this is a simple question, as I am new to coding and only familiar with password-ba ...

Arranging serialized information from a tabular format and retrieving specific data

: I'm currently attempting to utilize an AJAX POST request to send data from a dynamic webpage that includes information gathered from a table form, a date selection box, and comment text input. The webpage is generated as a PHP file on a GET request ...

Elements floating and creating gaps (caused by varying heights)

I am working on developing a responsive webpage. This is what I am aiming to achieve. View jsfiddle #container { max-width:500px; width:100%; color: #fff; } #one { width:300px; height:200px; background:#66BCD9; float:left; } #two { wid ...

What impact does including a parent View Tag have on the styling in React Native?

Why does adding a View parent break my styles? Could React Native's View tag have default styles that I'm not aware of? Displayed below is the Button component along with screenshots demonstrating the difference when using and not using the View ...

Unable to get CSS First Child Pseudo Element to Work Properly

I'm having trouble with this code in CSS and would appreciate any help. I can't figure out why the margin-left won't apply to the first i element. Below is the CSS I'm using: header.site-header .right_side_menu i:first-child { marg ...

Guide to placing an image below a <div> using HTML?

Before diving into the creation of my website, I took the time to draft a wireframe using Balasmiq. You can take a look at the wireframe here. Upon reviewing the wireframe, you'll notice that the first section bears a semblance to this layout: https:/ ...

Creating a stacked chart in Angular using chart.js with JSON array of objects values

I am currently working on implementing a stacked chart using chart.js, and I have encountered some challenges: I am struggling to display currency values in the correct format on the chart (the height of the bar is not visible when passing amounts). How c ...

Is it advisable to modify the value of props by using toRef in the Composition API?

I've noticed a common practice in the CompositionAPI where props are converted to refs using `toRefs` function. This has left me feeling a bit confused. For instance, citing the Vue 3 official guide: export default { props: { user: { type ...

How can I enable pagination in Datatables when the table HTML is generated using Angular after the drawCallBack function?

Below is the drawCallBack function I have implemented: "fnDrawCallback": function( oSettings ) { console.log("dt redrawn"); var selector = $("#example_table"); console.log(selector); function recompileForAn ...

jQuery script not correctly saving changes to database entries or updating dropdown menu choices

After testing the PHP scripts without jQuery and confirming they work, it seems like there might be an issue with my jQuery implementation. <form id="bakery" name="bakery" method="POST" action="bakeryupdate.php"> <select id="bakeryid" ...

Developing microfrontends using Angular involves loading and navigating a compiled package from npm

I have been struggling to find a solution to an ongoing issue and wasting time on futile attempts. Currently, I am working with Angular 15 within a microfrontend architecture. My goal is to implement a system where I can download a compiled microfrontend ...

Rule for restoring scroll position upon reloading web pages in browsers

When it comes to websites that handle data asynchronously, the behavior of scroll position restoration upon browser refresh can vary. Sometimes the scroll position is preserved, while other times it is not. For example, when reloading after scrolling down ...

Reasons why Custom CSS won't function simultaneously with Bootstrap 5

I recently designed a dashboard using bootstrap 5. While working on this project, I found myself in need of a custom CSS style in addition to the default bootstrap styles. However, I encountered an issue where my custom CSS would not apply properly unles ...