How to center an inline element using CSS and a background color

I'm struggling to center a block of text in a div with fixed dimensions both horizontally and vertically. I also want the text to have a semi-transparent black background and be able to stretch across two lines if needed.

The issue I'm facing is that the text isn't aligning vertically in the center, and the black background behaves oddly when the text wraps onto a new line.

Here's the current code I'm using:

HTML

<div class="description">
    <span>Welcome to the world of beautiful design, technology and music.</span>
</div>

CSS

div.description {
    width: 645px;
    height: 200px;
    margin: 0 auto;
    text-align: center;
}
div.description span {
    background: rgba(0, 0, 0, 0.5);
    color: #FFFFFF;
    font-size: 28px;
    line-height: 60px;
    padding: 10px;
}

I'd like to achieve a similar look to this example without relying on any complex JavaScript tricks to force it into two lines.

Thanks, Charlie

Answer №1

One of the most sophisticated approaches is to utilize display:table-cell;

This is how the CSS would look:

div.description {
    width: 645px;
    height: 200px;
    margin: 0 auto;
    text-align: center;
    display:table-cell; 
    vertical-align : middle;
}
div.description span {
    background: rgba(0, 0, 0, 0.5);
    color: #FFFFFF;
    font-size: 28px;
    line-height: 60px;
    padding: 10px;
}​

VIEW DEMO

Answer №2

An alternative method is to create a pseudo-table that enables the utilization of vertical-align: middle;. Check out this example here: http://jsfiddle.net/LcBbc/

Answer №3

To make adjustments in the margin-top and margin-left properties based on percentage values relative to the height and width of the window, utilize div.description.

For example: Replace

margin: 0 auto 

with

margin-top: 10%;
margin-left: 20%;

Answer №4

To perfectly center a div both vertically and horizontally, the most effective method is to utilize absolute positioning in CSS as shown below:

<div class="content_container">
    <div class="content">
        Welcome to a world filled with stunning design, cutting-edge technology, and captivating music.
    </div>
</body>

Here is the corresponding CSS code:

.content_container {
    position: relative;
} 
.content {
    width: 640px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -320px; /* half of the width */
    margin-top: -100px; /* half of the height */
}

This technique creates a fixed-size div that is centered both vertically and horizontally.

If you require the text to wrap on multiple lines, determining the height dynamically becomes necessary. In such cases, using JavaScript to calculate the height and adjusting the CSS values accordingly is preferred over relying solely on CSS.

For the background, employing a semi-transparent tiled PNG image is recommended for better compatibility across various browsers. Creating a small 5 x 5px image with desired transparency levels in software like Photoshop and saving it as PNG-64 format ensures optimal results.

Answer №5

If you're looking for a unique way to "center in the unknown," check out this interesting method I stumbled upon: http://jsfiddle.net/joplomacedo/ag5ea/

Here's the HTML snippet:

<div class="description">
    <span>
        Welcome to the world of creativity and innovation,<br />
        where design meets technology.
    </span>
</div>​

And here's the accompanying CSS code:

.description {
    width: 645px; height: 200px;
    margin: 0 auto;
    text-align: center;
}

.description:before {
    content: "";
    display: inline-block;
    height: 100%;
    margin-right: -0.25em;
    vertical-align: middle;
}

.description span {
    display: inline-block;
    vertical-align: middle;
}

I can't take credit for this brilliant technique—it was actually featured on css-tricks.com. Check it out here: http://css-tricks.com/centering-in-the-unknown/

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

Using JavaScript to Show Variables When Clicked

I have been working on populating multiple divs with data stored in variables that change when an image is clicked. Here's a snippet of the code within my tag:</p> <pre><code>function displayName(name){ document.getElementById( ...

Use jQuery to place tags around the content of existing <li> elements

Using jquery, I have been able to successfully create a list by using the following code: $(list).append(item); (where list is the list reference and item consists of the $('<li>') elements being added). var item = $('<li>' ...

Ways to position two images in the center

A website has been created by me and now I am looking to center text on the two images in the header. Here is the relevant code snippet: <div class="header"> <img src="css/title578145459.png" class="headerImage left&qu ...

Displaying items in the shopping cart across two separate columns

I have a website located at Within that page, I have included the Cart table using a woocommerce shortcode. Currently, the cart table is positioned below the billing details and payment options section. My goal is to move this cart table to be situated ...

Troubleshooting image overlay alignment concerns

My script successfully adds the image src to the overlay's image, but I encounter a problem when creating the variable imgH for the margin-top value. It calculates the image's height and divides it in half. The issue arises when the calculated h ...

Issue with toggling behavior of dynamically generated <div> using jQuery

My issue involves managing the behavior of dynamically generated <div> elements on my webpage. I am struggling to control these elements as intended. I have implemented an onclick Toggle function to show/hide the div Panel. However, since all the dyn ...

Attaching the CSS file to the Haml layout template

I'm currently working on linking a css file to a haml layout template Within the ApplicationHelper class, I have a method to properly generate html module ApplicationHelper def styletag(sheet_name) "<link rel='stylesheet' href=&a ...

Looking for assistance with a straightforward CSS opacity fix for Internet Explorer

Take a look at this page comparison between chrome and IE. On the right side, you'll notice drop down fields. While Chrome displays them correctly, IE shows rectangular boxes instead. To fix this issue, I added opacity to the select fields with the ...

Display the toggle button for expanding/collapsing text only when the length of the string exceeds 50 characters

Is there a way to only show a "read more/less" button in a table if the content exceeds 50 characters? The table contains a mix of content, some short announcements with about 10 characters and others with over 100. <div class="col"> <span ng-c ...

Is there a way to create a clickable component for triggering an AJAX call without using a Submit button?

Just starting out with JS/JQuery programming, so please excuse any mistakes or unclear explanations. Any feedback is welcome, even if not requested specifically. I am working with multiple drop down lists that are populated dynamically by data from SQL Ta ...

The hover effect is being applied exclusively to the final React component

When using next.js and tailwindCSS for styling, I created a custom component that includes tags. The issue arises when multiple instances of this component are placed on the page, as only the last one is getting the desired hover effect. "index.js" import ...

Utilizing the active tab feature within CSS

I am currently working with a detailed structure of bootstrap theme classes. Currently, I am in the process of designing a menu. This is the code snippet for the navigation bar design in Bootstrap- <div class="navbar navbar-fixed-top navbar-invers ...

dividing Handlebars HTML content into different files or sections

I am looking to design a single route webpage, but I would like to divide the HTML code into multiple files. When rendering this particular route, my goal is for the rendered file to pull content from different template files and combine them into one coh ...

What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario: https://i.stack.imgur.com/we05U.png In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in t ...

Challenges in customizing the bootstrap navigation bar links

Having an issue with the bootstrap navbar link displaying on small devices. Here is the template I'm using: https://i.sstatic.net/jSy1b.png The last item is displaying in two lines. ...

Using jQuery to add a class to an image element when the source attribute contains a specific

I have a bunch of text that looks like this <div id="justThisDIV"><p>Some paragraph <img src="http://mydomain.com/image.jpg"/> </p> <p><img src="http://mydomain.com/wow.png"/></p> <p><img src="http://notm ...

Validation is not being applied to the radio button

Link: Issue with Form I've encountered a problem with my script that is meant to validate and submit a form, similar to this working example: Form in Working Order Unfortunately, the script is not functioning as intended on the first link. The Java ...

Difficulty in altering the background of an input box

I am attempting to design a textbox that changes its background color to green when the correct answer is submitted, and to red for an incorrect answer. Unfortunately, nothing is happening for either option. document.querySelector('form').addE ...

With jQuery's .text() method, it is possible to modify the first span's Bootstrap class, but not the

As someone who is new to javascript, html, and jquery, I have been trying to change the text of 2 span elements in the same div using jquery's .text() command. Despite going through various solutions provided by different questions, none seem to work ...

What is the best way to align the bottom of an anchor element with the bottom of an SVG element when positioning them together

I am working on a test website where I am trying to create an interesting visual layout. My goal is to place an SVG image in the background, with an anchor element and other elements laid out above it. The challenge I am facing is aligning the bottom of th ...