Content contained within a rectangular box, adorned with ellipsis marks and centered alignment

My containers contain dynamic content with multiple lines of text. I want to display ellipsis (...) when the text exceeds the container size. Additionally, I aim to vertically align the text in the middle.

I have set up a Codepen http://codepen.io/anon/pen/ewnxG which includes the following HTML:

<div class="vertically-centered">vertically centered with</div>
<div class="vertically-centered">vertically centered with hello</div>
<div class="vertically-centered">one line</div>

Accompanied by this CSS:

.vertically-centered {
  border: 1px solid red;
  height: 6rem;
  overflow: hidden;
  font-weight: bold;
  font-size: 2.5rem;
  text-overflow: ellipsis;
  width: 300px;
  line-height: 1.2;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.vertically-centered:after {
  content: "";
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}

In IE11 and Firefox, the ellipsis "..." are missing, which is acceptable for me. However, it works fine in Safari and Chrome.

The challenge arises with the first div where the text gets cut off. The second and third div work as intended. This inconsistency based on text length prompts me to seek a solution without having to resort to JavaScript. How can I overcome this issue?

Answer №1

Take a look at this straightforward solution without any extra markup:

.vertically-centered {
    border: 1px solid red;
    height: 6rem;
    overflow: hidden;
    font-weight: bold;
    font-size: 2.5rem;
    text-overflow: ellipsis;
    width: 300px;
    line-height: 1.2;
    display: flex;  /* allows centering for modern non-webkit browsers */
    flex-direction: column;
    justify-content: space-around; /* centers for modern non-webkit browsers */
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    -webkit-box-pack: center; /* automatic centering in -webkit-box! */
}
<div class="vertically-centered">vertically centered with</div>
<div class="vertically-centered">vertically centered with hello</div>
<div class="vertically-centered">one line</div>
You can test out this solution by viewing the updated example on CodePen.

How it functions: Your original code already utilizes Flexbox layout for WebKit-based browsers (despite being outdated 2009 syntax), yet unfortunately, -webkit-line-clamp no longer works with newer implementations. Flexbox has its own mechanism for vertical centering. To achieve the desired behavior in WebKit-based browsers, simply remove the :after pseudo-element and replace it with the following line of code in .vertically-centered:

   -webkit-box-pack: center;

For other modern browsers like Firefox 22+ and IE11+, you can achieve the same layout (excluding the ellipsis) using the new version of Flexbox:

   display: flex;
   flex-direction: column;
   justify-content: space-around;

This should be placed above display: -webkit-box in the code so that WebKit browsers can still apply -webkit-line-clamp.

To make it compatible with IE10, add its prefixed version of Flexbox (2011 transitional syntax):

   display: -ms-flexbox;
   -ms-flex-direction: column;
   -ms-flex-pack: center;

You can find the pen with IE10 support here: http://codepen.io/anon/pen/otHdm

The :after method for vertical centering did not work in the first 'cell' due to the following reason: for inline-level CSS boxes (like standard text, inline blocks, images, etc.), vertical-align adjusts the baselines of all such boxes forming a line box. The height of the line box is calculated so that all inline-level boxes fit into it, making it impossible for the line box's height to be shorter than the tallest inline-level box within it. Therefore, your :after inline block, which takes up 100% of the container height, becomes the tallest element in the last line of your block. Due to vertical-align: middle, the baseline of the last line's text aligns with the vertical middle of the text and the tall inline-block. This scenario is fine when there is only one line (the usual case for centering) or when the last line is hidden with overflow, but it causes issues when visible).

Answer №2

Here is an easy solution that you can use:

.centered-vertically {
  margin: 0 auto;
  border: 1px solid blue;
  font-size: 40px;
  width: 250px;
  display: -webkit-flex;
  -webkit-align-items: center;
}

.centered-vertically p {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  max-height: 90px; /* specify maximum height for IE */
}

For the following markup structure:

<div class="centered-vertically"><p>centered vertically with text</p></div>
<div class="centered-vertically"><p>text centered vertically here</p></div>
<div class="centered-vertically"><p>single line text</p></div>

Check out this example: http://codepen.io/srekoble/pen/pHgjf

By enclosing your text within a p tag, you can use the truncate method on the p tag and align it vertically using the div tag.

Answer №3

To accomplish this, some adjustments to the markup will be necessary.

  • Include additional div elements around the text
  • Add a .vertically-centered div selector with these rules:
    • display: inline-block; as a fallback for non-webkit browsers, necessary for vertical alignment
    • display: -webkit-inline-box; for webkit browsers
    • max-height: 100%; to ensure the div is only as tall as the text if it's smaller than the container and as tall as the container if it becomes larger
    • vertical-align: middle; to center the div within the container vertically
  • Transfer the ellipsis-related rules from .vertically-centered to .vertically-centered div

Why is the extra div necessary?

The text on its own is inline, so only the last line is vertically aligned to the pseudo element :after. Therefore:

  • The first example appears incorrect because the "centered with" line is being vertically aligned to the middle of the pseudo element.
  • In the second example, the hidden "hello" is vertically aligned, while the rest of the lines fit in the box nicely regardless.
  • Using this method, the third example is the only one actually vertically aligned in the middle.

To see this clearly, change .vertically-centered:after to .vertically-centered:before, and you'll notice that now the first line "vertically" is centered.

By adding the extra container, all text contents can be vertically aligned instead of just one line.

Code Pen: http://codepen.io/anon/pen/htbxA

.vertically-centered {
        border: 1px solid red;
        height: 6rem;
        overflow: hidden;
        font-weight: bold;
        font-size: 2.5rem;
        width: 300px;
        line-height: 1.2;
    }

    .vertically-centered:after {
        content: "";
        height: 100%;
        display: inline-block;
        vertical-align: middle;
    }

    .vertically-centered div {
        display: inline-block;
        display: -webkit-inline-box;
        max-height: 100%;
        vertical-align: middle;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
    }
<div class="vertically-centered"><div>vertically centered with</div></div>
    <div class="vertically-centered"><div>vertically centered with hello</div></div>
    <div class="vertically-centered"><div>one line</div></div>

Answer №4

I made some adjustments to your CSS code. I included padding in the .vertically-centered div and specified the width of the .vertically-centered:after div to solve the issue. It seems like the problem was caused by the lack of a defined width in the .vertically-centered:after div. Below is my modified solution:

.vertically-centered {
    border: 1px solid red;
    height: 6rem;
    overflow: hidden;
    padding: 10px;
    font-weight: bold;
    font-size: 2.5rem;
    text-overflow: ellipsis;
    width: 300px;
    line-height: 1.2;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

.vertically-centered:after {
    content: "";
    height: auto;
    width: 100%;
    display: inline-block;
    vertical-align: middle;
}

I hope this solution works for you!

Answer №5

By enclosing the text within div tags and placing it inside <p></p>, along with incorporating the following CSS code:

.vertically-centered p {
  margin: 0;
  display:block;
  transform: translateY(-50%);
  top:50%;
  position:relative;
}

You should achieve the desired outcome.

Answer №6

If you want your code to be compatible with Internet Explorer, it may not be possible.

Check out some examples that do work in IE here:

  • Fade Out Way (CSS!)
  • Clamp.js Way (javascript)
  • TextOverflowClamp.js Way (javascript)

Personally, I prefer using

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

Having trouble with loading background images in the style tag of Vue.js. Can anyone offer a solution?

I have exhausted all options in my Vue app, but I am still unable to load the background image in my app.vue file. Despite getting the .html file to work with it, the image just won't show up. I've scoured the internet for solutions without succe ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

Another inquiry about bootstrap: Adjusting vertical height only if content does not overflow

My current setup is as follows: <div class="container px-0"> <nav class="..."> </nav> <div class="row px-3"> ...content </div> <div class="row footer-spacer&q ...

Creating a custom jQuery and HTML5 application for the WP8 device (specifically the Lumia 920) with a GWT framework that addresses the vertical CSS

Issue: I am facing an issue with scrolling out of application boundaries and trying to find a solution: (Image source: Prevent scrolling out of CordovaView in Cordova for Windows Phone 8 ) Method #1 body { overflow: hidden; -ms-content-zooming: ...

Assign a class to an element depending on its position using JavaScript/jQuery

<ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul> How can I use jQuery to add a class to the second li element in the list without using an existing class or id? ...

What is the best way to create a scrollable table that extends to 100% of the available width within its container, without taking up the

In the application, there is a collapsed sidebar on the left labeled "sidebar-left" and a container on the right with various types of content labeled "content." The issue arises with the width of this container, as it needs to take up 100% of the remainin ...

Locating and clicking a button within a table using Selenium WebDriver with Java, along with an event listener

This is my first question on Stack Overflow and I have not made any progress after a day of research. I am currently experimenting with WebDriver in Netbeans for testing our services. We chose WebDriver because we will need to test file uploads in the fut ...

What is the best way to emphasize a label upon clicking a radio button?

I am trying to update the label of a radio button when it is clicked, but I have been unsuccessful so far. I came across this answer which seemed promising, but it did not work for me. Here is my code: HTML <div class="same-line"> <input typ ...

Enhance Your Website with a jQuery Plugin for Dynamic Updates to ElementsgetPost

Is there a way to update the content inside an element by passing a new value to the public method updateText? Currently, when I try to pass a new string to the updateText method and click the button, only the method name is received as an argument instea ...

The applet failed to load on the HTML webpage

I'm having trouble getting this applet to load on an HTML page. I've already added full permissions in the java.policy file and I'm using the default HTML file from NetBeans Applet's output. /* Hearts Cards Game with AI*/ import java.a ...

jQuery - Event cannot be triggered on the 'deselect' or 'focusout' of <option> tag

Check out the demo here Hello there, I have a situation where I need an input box to appear below a select option, only if the user selects "Other". The code currently uses the .click() function on the option, but now I am trying to make the input box di ...

Error encountered when using the $.post function

$(".eventer button[name=unique]").click(function() { console.log('button clicked'); thisBtn = $(this); parent = $(this).parent(); num = parent.data('num'); id = parent.data('id'); if(typeof num ! ...

changing the visible style of a div element using JavaScript

I'm having an issue with a link on my webpage that is supposed to show or hide a <div id="po" style="display:none;">some html</div> element. The first time I click the link, the div displays properly. However, after tha ...

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

What could be causing the child element in CSS to be larger than its parent element when sorting?

I am working with a UL that contains multiple LI's. Within each li, there is a table. Using mootools, I have made my li elements draggable/sortable. However, I only want a small portion of the li element (and its child table) to be draggable. I atte ...

What is the best way to set individual heights for elements within a grid layout?

https://i.sstatic.net/BRdEx.png This container presents a challenge. The last element in the grid, which has a table-like structure, appears strange. Indeed, it looks odd because it is taking on the maximum height of the element present in that row. ...

Extract the content of a div element and update its numerical value using Selenium WebDriver in Java

In Java, while creating test cases with Selenium, I am stuck at a point where I need to extract the text from a div element and increase its numeric value by 1 to use it for later comparison. For instance, <div id="some_id">#27</div> If the ...

Issue encountered with fetching multiple data from database using checkboxes and a submit button

I am facing an issue with my shop page. I have the categories listed in checkboxes, and below that, I want to display only the checked categories after pressing the submit button. However, I'm not getting any feedback upon submission. When I replace ...

Send the completed form to a designated web address

Here's the form I'm working with: @using (Html.BeginForm("Search", "Home", FormMethod.Get, new { enctype = "multipart/form-data", @class = "navbar-form navbar-left form-inline", @role = "search" })) { var numberOfVi ...