Ensuring text is perfectly centered within a div, regardless of its length

In the quest to center text of unknown length within a div, challenges arise. Constraints limit its size to a certain extent, making it unclear whether one or two lines will be needed. As such, traditional methods like line-height are not viable options. Attempts with display: table-cell prove futile as they disrupt the layout. Certain positioning tricks using top cannot be employed due to other positional requirements.

To better understand this dilemma, refer to the following example.

Visual Representation:

The Original Code:

HTML:

<div class="background">&nbsp;</div>
<div class="TileText">MyText - Another long, long, long text</div>

CSS:

.background{
    background-color:#000;
    height: 400px;
    width: 100%;   
}

.TileText{
    position: relative;
    top: -135px;
    max-width: 200px;
    height: 80px;
    background-color: #FFF;
    color: #black;
    clear: both;
    padding-left: 10px;  
}

The Current State:

HTML:

<img src="images/castle.png" width="300" height="333" title="Castle" alt="Castle" />
<div class="TileTextWrapper">
    <div class="TileText">Text</div>
</div>

CSS:

.TileTextWrapper{
    position: relative;
    top: -135px;
    max-width: 200px;
    height: 80px;
    background-color: #FFF;
    color: #57abe9;
    clear: both;
    padding-left: 10px;
    display: table;
}

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

An Update:

The text is now vertically aligned properly. However, concerns persist regarding browser compatibility when using display: table.

Answer №1

Your fiddle has been updated:

It appears to be functioning correctly

Take a look: http://jsfiddle.net/hSCtq/11/ for reference.

I recommend placing .TileText within .background. Adding an empty div purely for a background image is not semantically accurate and often unnecessary. The only instance where a separate div might be useful is if you need to adjust the opacity of the background image independently from the content.

<div class="background">
    <div class="TileText">MyText - Another long, long, long text</div>
</div>


.background {
    background-color:#000;
    height: 400px;
    width: 100%;   
    display: table
}

.TileText{
    max-width: 200px;
    display: table-cell;
    vertical-align: middle;
    color: #fff;
    clear: both;
    padding-left: 10px;  
}

Similar questions with the same solution.

How to center a pre tag horizontally and vertically without using tables?

Resolving the issue of centering an image in a fixed size div (image variable size)

You can also find a similar code structure by searching "center vertical text css" in Google, which aligns with the layout provided in my JSFiddle example.

Answer №2

Include a <p> element within the TileText container:

HTML

<div class="background"> &nbsp; </div>
<div class="TileText"><p>MyText - Another lengthy, detailed text</p></div>

CSS

.background{
    background-color:#000;
    height: 400px;
    width: 100%;   
}

.TileText{
    position: relative;
    top: -135px;
    max-width: 200px;
    height: 80px;
    background-color: #FFF;
    color: #black;
    clear: both;
    padding-left: 10px; 
}

.TileText p { 
    position:absolute;
    display: table-cell;
    vertical-align: middle

  }

View an example at: http://jsbin.com/ubixux/2/edit

Answer №3

For proper alignment, make sure to include display:table-cell; and vertical-align:middle;

Answer №4

In order to achieve vertical alignment, one must utilize a table within their code. Here is an example of how this can be done:

 <div style="width:500px; height:500px; border:#333333 1px solid;">

    <table style="width:100%; height:100%; vertical-align:center">
        <tr>
            <td>
    MyText - A lengthy description
            </td>
        </tr>
    </table>
</div>

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

problem when trying to establish the minimum height for a div element prior to the website being fully loaded, considering the

Having trouble with a CSS issue that seems simple but I can't find a solution for. I have a main div with a min-height set to a certain value, specified in %. Since there is no outer div, the min-height won't display if it's given in px. I ...

Canvas ctx.drawImage() function not functioning properly

I've encountered an issue while trying to display images in a canvas using my rendering function. Here is the code snippet: function populateSquareImages(){ for(var i = 0, ii = squares.length; i < ii; i++) { if(squares[i].hasImage) { ...

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...

Is there a way to maintain image proportions when resizing the window?

I'm in the process of developing a classroom-themed website with interactive overlaying images. The goal is to have various pictures that users can click on to access different resources from different websites. My main challenge right now is getting ...

dismiss data and button for closing notification bar

I am currently using a notification bar at the top of my website, instead of a modal. I am wondering if it is possible to click the X (close-button) and have the notification bar disappear. I attempted to use data-dismiss but it did not work. Also, how can ...

Tips for preserving user input from HTML into a text file and then reloading it back into the HTML document

I have recently created a character sheet for a game using HTML. The HTML file is mainly comprised of various input tags such as <input type="text">, <input type="number">, <input type="checkbox">, <input type="radio">, <select&g ...

Animations in Angular fail to operate within mat-tabs after switching back when custom components are being utilized

I am facing a similar issue as Olafvv with my angular 16 project. The problem occurs in a mat-tab-group where the :enter animations do not work when navigating away from a tab and then returning to it. However, in my case, the issue lies within a custom su ...

"Executing ng-click directive on a second click changes the route in AngularJS

Why does my ng-click only redirect to a new location on the second click? It should redirect to $location.path('/login.signin');, but it only works if I click the button again. It's strange. Where could this issue be originating from? Belo ...

Interactive pop-up messages created with CSS and JavaScript that appear and fade based on the URL query string

I have a referral form on this page that I want people to use repeatedly. After submitting the form, it reloads the page with the query string ?referralsent=true so users can refer more people through the form. However, I also want to show users a confir ...

Can someone point out the mistakes in my CSS Layout?

I've been struggling to make progress on this task over the past couple of days, encountering roadblocks with no clear solution in sight. The maze of nested divs I'm navigating through might be playing tricks on my mind, so having a fresh pair of ...

Implementing a distinct approach to adding margins to div boxes using

Hello, I've been experimenting with the developer tools in Google Chrome to add margins to my navigation bar. The goal is to create gaps between the boxes. Any assistance would be greatly appreciated! http://jsfiddle.net/3jp1d0fe/8/ CSS div.contain ...

disable input box stationary

Is there a way to make a checkbox stay disabled even after refreshing the page? Currently, when I click the checkbox it disables, but upon refreshing the page, it goes back to being enabled. $( "input[type='checkbox']").click(function(event){ ...

Display radio buttons depending on the selections made in the dropdown menu

I currently have a select box that displays another select box when the options change. Everything is working fine, but I would like to replace the second select box with radio buttons instead. Can anyone assist me with this? .sub{display:none;} <sc ...

When the mouse hovers over, include a fade-in effect for the image

I am working with two overlapping images and have successfully implemented a function to display the second image on mouse hover. However, I am struggling to incorporate a CSS transition property for a smoother image transition effect. Currently, when the ...

Creating a secondary title for a Bootstrap Navigation Bar

I have a unique Bootstrap 4 website that features a navbar. The navbar consists of a special brand section with an image and title text, followed by the rest of the navbar elements. You can view it here: https://jsfiddle.net/zmbq/aq9Laaew/218793/ Now, I a ...

What is the process of making circle or square shapes with text inside using React, without the use of SVG images?

Is there a way to create circle and square shapes in React with custom text inside, without relying on SVG images? Check out this example: I attempted the code below but it did not render any shapes: import React from 'react'; export default fu ...

Knockout text binding does not automatically update the width

Recently, I encountered a bug in an ongoing project where the user name was appearing within another element until hovered over with a cursor. Upon further investigation, I discovered that this issue stemmed from the project's usage of Knockout.js. I ...

Implementing icon display upon click in a Meteor application

Currently, I am in the process of developing an application using meteor and within one of the templates, I have the following code snippet. <h3> <b> <a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a> </b> ...

What could be the reason for my flex items not shrinking when the browser window size is decreased?

Here is the CSS code for the header component using flexbox: .header { display: flex; flex-direction: row; justify-content: space-between; padding: 15px 20px; background-color: #ffffff; position: sticky; top: 0; z-index: ...

Adjusting Bootstrap 4 Modal Transparency

Currently using Bootstrap 4 Beta and looking to darken the background when a Modal is displayed. I stumbled upon a solution suggesting the addition of a CSS class. .modal-backdrop.in { opacity: 0.5 !important; position: fixed; } The advice was no ...