Is it possible to vertically align variable length text within a container of fixed height?

One common method for centering text inside a div is to use the following CSS trick:

.center-div {
    display:table-cell;
    vertical-align: middle;
}

The issue arises when the text within the div varies in length and I require the container to have fixed dimensions. Attempting to adjust the CSS as follows results in unwanted behavior:

.center-div {
    display:table-cell;
    vertical-align: middle;
    width: 100px;
    height: 100px;
    text-overflow: ellipsis;
}

Since it is set as a table-cell, the height of the div changes instead of overflowing. Given that my text may span multiple lines, traditional line-height methods are ineffective. Is there a way to both center the text and allow it to overflow simultaneously?

P.S. I am seeking a CSS-only solution. The content will be generated by angularjs, making it difficult to determine completion of rendering. If JavaScript is absolutely necessary, please provide a method that can be integrated seamlessly with angularjs (specifically ng-repeat).

Answer №1

Content will be centered vertically within a fixed height and width. The word-wrap:break-word; property has been applied to the span element.

div.center-div
{
    display: table;
    table-layout:fixed;
    margin: 0 auto;
}

div.center-div span
{
    display: table-cell;
    max-width: 300px;
    height: 100px;
    vertical-align: middle;
    background: red;
    text-align: center;  
    word-wrap: break-word;
}

HTML

<div class="center-div">
     <span>
          Hello, world!
     </span>
</div>

View Demo

Answer №2

If you are looking to place your text inside a div with specific dimensions, here is a simple solution:

.center-div {
  width: 100px;
  height: 100px;
  position: relative;
  text-align: center;
  border: 1px solid #333;
}
.content {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  max-height: 100px;
  overflow: auto;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  -o-transform: translateY(-50%);
  transform: translateY(-50%);
}
<div class="center-div">
  <div class="content">Lorem ipsum dolor sit amet, consectetur.</div>
</div>

CSS:

.center-div {
   width: 100px;
   height: 100px;
   position: relative;
}
.content {
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    max-height: 100px;
    overflow: auto;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
}

Check out the CodePen Preview for more details.

Keep in mind that text-overflow: ellipsis will only work with white-space: nowrap; for single line text.

Answer №3

The CSS property text-overflow:ellipsis does not properly truncate multiline text. While there are some CSS-only workarounds with limited browser support, a more effective solution may involve using JavaScript implementations.

To center your text, consider wrapping it in a container element and applying styles such as line-height: 100px, display: inline-block, and max-height:100px to the content:

http://jsfiddle.net/ilpo/jwcyfwpw/

Answer №4

To achieve text overflow and vertical centering within a div container, you can nest an element inside the div to hold the text content. The div will then handle the sizing of the container.

Consider using the following structure:

HTML:

<div class="center-div-content">
    <div class="center-div">
        this is a sample text that may be long enough to cause overflow yet remain vertically centered
    </div>
</div>

CSS:

.center-div-content{    
    position: relative;
    display: inline-block;
    width: 100px;
    height: 100px;
}

.center-div {
    position: absolute;
    width: 100%;    
    top: 50%;
    text-align: center; //if you want center horizontal too

    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    transform: translateY(-50%);
}

You can view how the text behaves in different lengths while maintaining alignment and overflow in this FIDDEL.

Here's the link to the demonstration: http://jsfiddle.net/Yandy_Viera/qnmm1Lm5/1/

Answer №5

Sure, is this the solution you were looking for? be sure to wrap your text in a span

http://jsfiddle.net/ct9ey95k/1/

Feel free to add or remove text and see if it meets your requirements.

Answer №6

If you're not sure if this is exactly what you need, here's a helpful trick I use:

Here is the CSS code snippet:

.outer {
     overflow-x: hidden;
     overflow-y: auto;
     text-align: center;
     position: fixed;
     top: 0;
     left: 0;
     bottom: 0;
     right: 0;
}
.outer:after {
     content: "\a0 ";
     position: relative;
     display: inline-block;
     vertical-align: middle;
     top: 0px;
     left: 0px;
     width: 0px;
     height: 100%;
}
.inner {
     display: inline-block;
     vertical-align: middle;
     width: 70%;
     min-height: 100px;
     background: red;
}

And here is the corresponding HTML code:

<div class="outer">
  <div class="inner">
    Your Text ....
  </div>
</div>

You can view an interactive demo on Jsbin: http://jsbin.com/duwuzogodo/1/edit

In this setup, the inner layer is centered both vertically and horizontally within the outer layer (which is fixed in this example). If the text in the inner layer gets too large, it will overflow and be scrollable. This approach eliminates the need for using the table-cell hack and does not require any additional scripts.

Answer №7

This solution combines elements of previous answers with the addition of Bootstrap for vertical text centering.

Fiddle

HTML

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="dlink.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>


<div class="row my-row">
  <div class=" col-12 my-col container-w-header">
    <div class="col-12 my-col">

      <div class="ContainerSingle ">
        <div class="icon">
          <a href="http://placeholder.com"><img src="https://via.placeholder.com/72"></a>
        </div>
        <div class="labelContainer-overflow">
          <div class="row my-row align-items-center label-row">
            <div class=" col-12 my-col label-col">
              <div class="iconLabel-overflow">
                <span>
                  This long label may overflow from its box and displays an ellipsis
                </span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="ContainerSingle ">
        <div class="icon">
          <a href="http://placeholder.com"><img src="https://via.placeholder.com/72"></a>
        </div>
        <div class="labelContainer-overflow">
          <div class="row my-row align-items-center label-row">
            <div class=" col-12 my-col label-col">
              <div class="iconLabel-overflow">
                <span>
                  Experiment by varying the length of this text
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

CSS

.my-col { 
    /* border: 3px dotted blue;  */
    padding: 0;

}

.my-row {
    /* border: 3px solid red; */

}

.label-row {
    height: 72px;
    justify-content: start;
    align-items: center!important;

}

.ContainerSingle {
    text-align: center;
    display: inline-block;
    max-height: 72px;
    vertical-align: top;
}

.icon {
    display: inline-block;
    float: left;
    margin-right: 16px;
    height: 72px;
    width: 72px;
}

.labelContainer-overflow{
    display: inline-block;
    text-align: left;
    vertical-align: top;
    min-width: 124px;
    
    
}

.iconLabel-overflow span {
    max-width:124px;
    color: #707070;
    font-size: .85rem;
    line-height: 1.15rem;
    overflow: hidden;
    display: -webkit-box;
  -webkit-box-orient: vertical;
  
  /* <integer> values */
  -webkit-line-clamp: 4;
     

Answer №8

give this a shot...

HTML

<div class="center-div">
  <div class="content">text goes here text goes here text goes here text goes here text goes here text goes here text goes here text goes here</div>
</div>

CSS

    .center-div {
    display:table-cell;
    vertical-align: middle;
    width: 100px;    
    text-overflow: ellipsis;
    border:1px solid red;    
}
.content {       
    height: 100px;
    overflow: auto;
}

Check out the Fiddle Demo

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

The CSS styles are not recognized by the Windows 2003 server

After deploying my webapp, which was created using asp.net, to a testing server (Windows 2003 SP2, IIS6), I encountered an issue. When I accessed the default page, none of the CSS styles were applied. Only plain text or formatting from the .aspx file was v ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

How does Firefox still autocomplete even with a different input label?

How does Firefox decide where to autofill passwords and usernames? I've noticed that even after changing the name, id, title, or class of an input element, Firefox still automatically fills it with my password or email address. ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

Moving images displayed on a webpage

Is animating 5 pictures/photos a simple task? Take a look at this example: Which programming languages are recommended for achieving this effect? Thank you Tea ...

When making Axios GET requests, HTML receives promises that may remain empty

I've spent the entire day trying to figure out why this isn't working. Here's a simplified version of the HTML table using Vue v-for: <table id="timeSheet-datatable" class="table table-striped dt-responsive w-100"> ...

Running a repeated script

I recently discovered a fantastic script called Typer that creates a typewriter effect. However, I noticed that it does not have a built-in method to loop the animation once it reaches the end. Does anyone have any suggestions on how to achieve this? t ...

Unique Text: "Personalized marker/pin for interactive map feature"

Looking to create a custom image map marker/pin with a unique bottom design resembling a union shape using CSS and Vue.js. I've attempted it myself but haven't been able to achieve the exact look as shown in the reference image. Any advice or ass ...

Issues with the styling of C3.js

I'm encountering some issues with a visualization I'm trying to create using C3.js. The top and side edges of my scatter chart are getting cropped (likely due to changing the radius of the bubbles), but I don't believe that should be cau ...

Is it possible to use CSS and HTML to rotate a cube and expand its sides?

I am attempting to rotate the cube and expand its faces. I have experimented with the following code: .wrapper{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } .cube-wrap { width: 40px; height: 40px; ...

Search for the highest value from the dropdown list in real-time using Selenium with Python

Currently, I am utilizing Python along with Selenium to automate a certain application. My goal is to extract the top value from a drop-down menu, however, the values in the menu are constantly changing. This makes it impossible for me to input a static XP ...

Troubleshoot: JQuery unable to change background color in code

Is there a way to use JQuery to cycle through an array of colors and change the background color of a page whenever a specific button is clicked? I've tried implementing it with the following code, but it doesn't seem to work as expected. Here&a ...

Alphabetically sorting objects in an array using Angular

If your TypeScript code looks something like this: items: { size: number, name: string }[] = []; ngOnInit(): void { this.items = [ { size: 3, name: 'Richard' }, { size: 17, name: 'Alex' }, ...

Incorrect form of SphereGeometry detected in three.js

I'm having trouble rendering a simple sphere in three.js because it's appearing distorted (looking more like a vertical stick). Below is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

What is the best way to style odd and even divs in CSS?

I am struggling with applying different CSS styles to the odd and even divs in my code. The current implementation I have does not seem to be working as expected. I specifically want the styling to target only the direct children of the div, rather than an ...

What could be causing the "function undefined" error in my HTML document?

Recently, I developed a small chat application that initially functioned well with all code contained in one HTML document. However, after separating the CSS, HTML, and JS into individual files, an issue arose when invoking the register_popup function from ...

Changing the positions of objects on a resized HTML Canvas

I am currently developing a tool that allows users to draw bounding boxes on images using the Canvas and Angular. Everything was working smoothly until I encountered an issue with zooming in on the canvas causing complications when trying to draw bounding ...

"Create a Single-Page Bootstrap Website with a Responsive Design showcasing PHP Code within the Contact Form

Working on the final touches of a single-page responsive website project for a client. Utilizing a Bootstrap contact form located at the bottom of the HTML document. The PHP code is unexpectedly displaying in the text fields of the contact form. I've ...

Ways to determine whether an element is presently engaged in scrolling

Is there a way to determine if certain actions can be disabled while an element is being scrolled? The scrolling may be triggered by using the mouse wheel or mouse pad, or by calling scrollIntoView(). Can we detect if an element is currently being scroll ...

Personalizing navigation tabs using Bootstrap

I've been working on creating a custom bootstrap navbar tabs, but I'm struggling to remove the borders and apply the custom colors. After some trial and error, here's what I have so far: .nav-tabs, .nav-pills { text-align: center; bo ...