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

Modify the text and purpose of the button

I have a button that I would like to customize. Here is the HTML code for the button: <button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button> The corresponding JavaScript code is as follows: var search = n ...

Apply CSS styles when the text exceeds the size of the textbox

Is there a way to create a textbox that scrolls on hover only if the text is longer than the textbox itself? Check out my attempt here: https://jsfiddle.net/SynapticError/wqh4ts3n/35/ The text should scroll on hover if it's longer than the textbox. ...

Error: Issue with parsing integer in JavaScript

I'm in the process of developing a dice game that involves rolling two dice and determining the sum. The goal is to display the running total next to the dice. However, I'm encountering an issue where NaN (Not a Number) is being displayed. Here i ...

Tips for displaying a background image without obstructing the container class on your website

How can I set a background image for my website? Whenever I use the code background-image:url('path_to_image');, it ends up covering my container class. Is there a way to place the image behind the container class? ...

How to adjust the background picture opacity in HTML

Is it possible to adjust the transparency of a background image in HTML? I came across one solution that involved adding a box on top of the background picture and changing the opacity of the box, which in turn changed the opacity of the background pictur ...

"The application is experiencing issues with loading styles correctly when using jQuery append (Fiddler has been

When attempting to load a div tag using the .append() method, the styles are not loading correctly. Here's the code that was tested: <section id="year-2020" class="tab-panel"> <div class="row accordion"> <header> ...

Collecting data with Selenium as elements load [Python]

Is there a way to scrape only the newly generated items in sequence? I have a dynamic list that loads with scrolling. There are two methods I can use to scrape all generated divs: Scroll to the bottom of the list and then scrape all generated divs. Scroll ...

What is the maximum width allowed for a WordPress site on mobile devices?

I have been tasked with addressing the responsiveness issues on mobile for this particular site. However, I am struggling to understand why the website is displaying horizontal scrolling on the landing page in a mobile view. Any assistance in resolving t ...

Expanding the `div` element to visually occupy the entire vertical space

I'm facing a design challenge with my webpage layout. I have a fixed header and footer, but I need the content section to dynamically adjust its height between the two. The goal is to fill the remaining vertical space with a background-image in the co ...

What methods can we use to transform Bootstrap rows and columns to resemble a table design?

Attempt number one did not work due to padding issues in the columns. Attempt number two also failed, leading me to believe I may be making a mistake somewhere. This is what I am aiming for: Can anyone provide some assistance? I would prefer avoiding mo ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...

Tips for centering text inside a div using a separator

During my side project, I decided to use the angular material divider but encountered issues with aligning the text correctly. https://i.stack.imgur.com/zg1mu.png The problem can be seen in the image provided - the text on the right side is not aligned b ...

"Pressing the 'back' button on your browser takes

Is there a way to navigate back to the main page by clicking on an image? After selecting First, Picture1 will be shown. How can I go back to the selection page for further choices? <a href="picture1.jpg"> <h3>First</h3></a> <a ...

Is there a way to adjust the text color of a label for a disabled input HTML element?

If the custom-switch is active: the label text color will be green. If the custom-switch is inactive: the label text color will be red. A JavaScript (JQuery) method call can be used to activate one button while deactivating another. The Issue It appe ...

Ensuring that the image perfectly fills the entire screen on an iPhone X using React Native

Looking for a solution to make my image fit the entire screen on the iPhone X simulator. I've tried adjusting the imageContainer width to "100%" and the container that encompasses everything, but haven't had any luck. Would appreciate any suggest ...

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Using npm webpack-mix to execute a JavaScript function stored in a separate file

Currently, I am facing a challenge with accessing a function that is defined in the table.js file from within my index.html. Here is a snippet of the code: table.js let table; function set_table(table) { this.table = table; consol ...

What is the best way to ensure a div element on a printed page has a space between its bottom edge and the physical paper, as well as a space between its top

Within my div element lies a collection of other div elements. These elements contain lengthy text that may span multiple pages. I am attempting to print this text starting 50mm from the top edge of every physical paper, and stopping 20mm before the edge o ...

Execute jquery commands after the function has finished

I am trying to implement the code below: $(":file").change(function () { if (this.files && this.files[0]) { console.log(this.files[0]); var reader = new FileReader(); ...