How to center text both horizontally and vertically in HTML

I am struggling with centering a background image along with a 1-line text vertically and horizontally inside a div. Although I have successfully centered the image, the text remains misaligned. I attempted using vertical-align: middle without success.

Below is my current code:

<div style="background: url('background.png') no-repeat center; width:100%; height:100%; text-align:center;">
   <div style="color:#ffffff; text-align: center; vertical-align:middle;" >
       Some text here.
   </div>
</div>

Any solutions or tips?


In a temporary fix, I resorted to utilizing a table, even though it might not be recommended by some in the HTML community. Is there a specific reason why using tables for layout should be avoided? I am still interested in learning how to achieve the desired effect using divs.

 <table width="100%" height="100%">
   <tr>
     <td align="center" style="background: url('background.png') no-repeat center; color:#ffffff;">Some text here.</td>
    </tr>
</table>

Answer №1

Typically, to horizontally center a block element, you would use the following code:

div.inner { margin: 0 auto; }

Important: This method may not work in IE quirks mode, so it's best to always include a DOCTYPE declaration at the beginning of your HTML document to ensure standards compliance.

Vertical centering, on the other hand, can be more challenging. For solutions, you can check out Vertical Centering in CSS

Answer №2

Centering div content vertically in CSS can be a bit tricky, as there is no direct method to do so. However, there are alternative approaches that can achieve the desired result. Check out this link for more information

If you're looking for solutions to center a div vertically across all browsers, there are numerous discussions on the same topic on platforms like SO. Learn more about how to achieve vertical centering with CSS here.

Answer №3

If you find yourself in a situation where you need to restrict text to only one line within a fixed-height parent div, consider using the line-height property in CSS. For example, if the parent div has a height of 500px, you can set the line-height to be equal to that value with CSS: line-height: 500px;.

Answer №4

When it comes to positioning photos and captions centered without using javascript libraries like thickbox, I have experimented with a couple of solutions. One approach that I found was:

<body style="height:200px; min-height:800px;">
   <div style="background: url('background.png') no-repeat center; height:100%;">
      <div style="text-align: center; position:relative; top:50%; color:#fff;">
         Some text here.
      </div>
   </div>
</body>

It's worth noting that in this setup, a specific height had to be defined for the container (the BODY element or possibly a wrapper DIV). In older versions like Explorer 6, setting the BODY height to 100% may work, but in modern browsers like Firefox, this approach might not yield the desired outcome.

EDIT:

I came across an improved solution which involves:

<style type="text/css">
    html, body {height:100%;}
</style>
</head>
<body>
    <div style="background: url('background.png') no-repeat center; height:100%;">
        <div style="text-align: center; position:relative; top:50%; color:#fff;">
            Some text here.
        </div>
    </div>
</body>

Answer №5

To achieve VERTICAL centering, one suggestion is to use a table within the DIV, as recommended by Cletus as other methods may be more complex.

div.centered table {margin: 0 auto;} /* no width needs to be specified for table */
div.centered table td {vertical-align: middle;} /* change to vertical-align: top; to disable vertical centering */


<!-- borders added only to help understanding -->
<div class="centered" style="border: 1px solid #cccccc;">
    <table style="border: 1px solid #ff0000;">
       <tbody>
          <tr><td>
             Some text here
          </td></tr>
       </tbody>
    </table> 
</div> 

If you are looking for HORIZONTAL centering (without vertical), you can simply use a DIV:

div.centered div {margin: 0 auto; width: 300px;} /* specify a width to center a DIV */

<!-- borders added only to help understanding -->
<div class="centered" style="border: 1px solid #cccccc;">
    <div style="border: 1px solid #ff0000;">
       Some text here
    </div> 
</div> 

For horizontal alignment of a DIV inside another DIV, a fixed width for the inner DIV is necessary. If this is not ideal, using the first solution with a table and removing "vertical-align: middle;" for only horizontal centering may be easier.

This method was tested in document type:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

tested on IE7, FF 3.6, SAFARI 4.0.4

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

Pressing the button will allow you to select and copy the text within the

I am looking to incorporate a mock-chat feature into my website. The concept is to type something on the website, then click a button next to it which will move the text to a frame above. I attempted this using a textarea and even found a code for selectin ...

Empty screen appears when "npm run serve" command is executed following the build process

I am currently utilizing Material-ui. Following the project build with npm run build, I encounter a blank page when running npm run serve. I attempted to set homepage: "./" in the package.json as suggested here, however, it still displays a blank ...

Can IE(7?) cause distortion of backgrounds from sprites?

This task is giving me a headache. We're almost finished with revamping our website. The last step involves consolidating all the glyphs and icons into a sprite. These images are transparent .png files, so we made sure the sprite maintains transparen ...

`Carousel nested within tabbed interface`

I am currently facing an issue with my website's tabs and carousels. I have 4 tabs, each containing a carousel, but only the carousel in the first tab seems to be working properly. When I activate the second tab, all the carousel divs collapse. For r ...

Issue with Dynamic Image Path in Require Function: Unable to locate the relative module

I've been struggling with an error in VueJs require function for the past two days. I'm attempting to pass a prop to the Home component and then display the image. Home.vue <template> <BlogPost :post="welcomeScreen"/> <B ...

Tips for accessing CSS properties on the img tag

I could use some assistance with CSS. I am in the process of creating a tree structure using many <ul> and <li> tags. The issue arises when I have multiple <li> elements with a specific class, each containing an <img> tag. How can ...

I am looking to adjust/modulate my x-axis labels in c3 js

(I'm specifically using c3.js, but I also added d3.js tags) I have been working on creating a graph that displays data for each month based on user clicks. However, I am facing an issue where the x-axis labels show 0-X instead of 1-X. For instance, ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

Create a dynamic and interactive website using a combination of jQuery and AngularJS

I recently came across an interesting tidbit on the FAQs of Angular stating that "Angular can use jQuery if it's present in your app when the application is being bootstrapped". This got me thinking, is it considered a best practice to include both j ...

Issue with rendering images on Bootstrap-Vue card component

In the process of creating a static website with Vue.js, I am attempting to incorporate a basic Bootstrap card using Bootstrap-Vue. Unfortunately, I am facing an issue where the image does not display when utilizing the b-card component with the img attrib ...

Creating a vertical scrollable content using FlexBox

Struggling to create a scrollable box using flex The Box element with the id=scroll is not behaving as expected, causing content overflow How do I set the Box to overflow=auto and enable scrolling for the content? Spending countless hours trying to unrav ...

Tips for styling your Angular Material Card on mobile devices

Currently, I am very happy with my desktop layout which looks like this: https://i.stack.imgur.com/tG0pw.png However, when it comes to the mobile version of my site, here is what I have so far: https://i.stack.imgur.com/KD1hh.jpg While I do like the ho ...

What steps should I follow to create a cohesive background design using CSS?

Is there a way to combine two separate div elements in CSS? Currently, the image Row and col are not connected to the above SVG blob. How can I utilize the blob as a background? Based on the code provided below, they appear separated and I'm unsure ho ...

Centering bootstrap columns in a WordPress template

I am facing an issue with aligning columns in a bootstrap section within a Wordpress template that I am working on. The problem is that the columns on the second line of the row are not centered. Currently, the layout displays 4 columns in the top row and ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...

Shooting star css animation featuring pre and post effects

Trying to create a falling star using CSS animation. I made a star with a pseudo element, but I'm having trouble setting the animation in the pseudo-element. i{ position: relative; width: 0; height: 0; border-left: 12px solid transpa ...

Finding a predecessor with Selenide through tag and class identification

Trying to find the ancestor element using Selenide library on a website. The ancestor element is <div class="BorderGrid-cell" ...>. The .closest(".BorderGrid-cell") method works well. However, the .closest("div.BorderGrid-ce ...

Enhancing JQuery UI Accordion with simple ICONS

Is it necessary to use the Jquery CSS file for adding icons, or is there an alternative method? I'm hoping I can avoid using it as I am working within Wordpress and enqueuing the Jquery CSS seems like a complex task for me. Apologies for the basic q ...

What is the best way to rearrange Bootstrap columns for mobile devices?

I have 4 columns displayed like this on desktop, and I want them to rearrange to look like the following on mobile. Do I need custom CSS for this? (I can't post images yet, so here is the link to the image: https://i.sstatic.net/b0gUZ.jpg I've ...

Automated scrolling effect within a container element

I am working on a div container named wrapper2 that houses a chat interface. Inside the container, there are five messages in a div called chatleft, each containing images. The height of the wrapper2 div is smaller than the combined height of all the messa ...