Having trouble with aligning middle of absolutely positioned block text vertically

I'm facing an issue with aligning h2 text vertically in the middle of a block.

The situation is that I have multiple images with different heights but the same width (300px), each with varying amounts of text that may span over several lines and appear on top of the image when hovered over.

My goal is to vertically center this text...

Here's a demo:
http://jsfiddle.net/wn3Kj/2/

<div class="post-thumb">            
      <a href="http://eclectivism.com/text/">
          <h2 class="entry-title">Text text  text  text  text  text  text  text  text text text text text text text text text text text text text text text</h2>
          <img src="http://eclectivism.com/wp-content/uploads/2013/09/space-doodle-01-580x7041.jpg" class="attachment-blog-large wp-post-image" />
      </a>
</div>

CSS

.post-thumb {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent; }

a {position: relative; display: inline-block; }

h2 {
    opacity: 0;
    padding-right: 20px;
    padding-left: 20px;
    padding-bottom: 0px;
    padding-top: 50%;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: 0;
    background: rgba(214,238,219,0.8);
    color: #fff;
    text-decoration: none;
    text-shadow: 0px 1px 5px rgb(63, 97, 56);
    text-align:center;
    display:block;
}

img {
    width: 300px;
}

a:hover  h2 {opacity:1}

Answer №1

Here is a solution that does not require JavaScript.

To add a background element in HTML:

<div class="post-thumb">            
      <a href="http://eclectivism.com/text/">
           <span class="post-thumb-highlight"></span> <!-- Add your extra element here -->
           <h2 class="entry-title">Text text  text  text  text  text  text  text  text text text text text text text text text text text text text text text</h2>
          <img src="http://eclectivism.com/wp-content/uploads/2013/09/space-doodle-01-580x7041.jpg" class="attachment-blog-large wp-post-image" />
       </a>
 </div>

Style the added element with CSS:

.post-thumb-highlight {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    background: rgba(214,238,219,0.8);
    opacity: 0;
}

h2 {
    opacity: 0;
    text-decoration: none;
    display: inline-block;
    color: #fff;
    text-decoration: none;
    text-shadow: 0px 1px 5px rgb(63, 97, 56);
    text-align:center;
    width: 300px; /* same width as IMG */
    vertical-align: middle;
    margin-right: -300px; /* negative value of IMG width */
    position: relative;
    font-size: 24px;
}

img {
    width: 300px;
    vertical-align: middle;
}

a:hover h2, a:hover .post-thumb-highlight {opacity:1}

For a demo, visit http://jsfiddle.net/3epgP/1/

Answer №2

To align a div in the center both vertically and horizontally, you can achieve it using this JavaScript code:

 $('.dialogdiv').css('top', Math.max(0, (($(window).height() - $('.dialogdiv').outerHeight()) / 2) + $(window).scrollTop()) + 'px');
 $('.dialogdiv').css('left', Math.max(0, (($(window).width() - $('.dialogdiv').outerWidth()) / 2) + $(window).scrollLeft()) + 'px');

I trust this solution is helpful to you.

Answer №3

To achieve center alignment in CSS, include the following:

left: 50%
top: 50%

Remember to subtract half of the text's width and height for margins.

For instance:

HTML:

<div>
<h3>Greetings</h3>
</div>

CSS:

div {
height: 500px;
width: 500px;
}

h3 {
height: 50px;
width: 100px;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -25px;
}

This code snippet will effectively center the text within the div element.

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

Why isn't the z-index functioning properly in Vue.js styling?

I am currently developing a simple component that displays four steps, indicating the current step and allowing users to navigate through them. I want to create a design where these numbers are enclosed within circles that are evenly distributed in a line ...

I am trying to verify my code, but the messages are not displaying under the username. They only appear under the password field. I am not sure where I have made a mistake

Having trouble with my login form validation using jQuery. Can someone help me fix it? $(document).ready(function() { $("#form1").validate({ rules: { username: { required: true, minlength: 6 }, password: { ...

Strange Behavior of Json Dataset

I've noticed some unusual behavior when loading JSON data via AJAX with an interval. Initially, the data loads correctly, but after a few intervals, it starts to get scrambled and runs unpredictably between intervals. This issue even leads to crashes ...

Ensure the vertical dimension of the webpage is properly maintained

I am currently working with a client who has requested a website design with a specific height for the content section. The Inquiry: Is it possible to automatically create a new page for text that exceeds the maximum height of the content section on the ...

Internet Explorer displaying incorrect formatting for HTML CSS tables

Having an issue with table display on IE 9/10/11. Tested code on different browsers and platforms, everything looks good except when viewed on my HTTP server (lighttpd and python SimpleHTTPServer), the table is showing up incorrectly: var cell = $(&apos ...

the frame on the page is distorting

I am trying to implement a frame around my website that overlaps elements. desired appearance Although I created a styled div for the frame, it seems to have a bug and looks like this: current appearance Below is the React code I am using: class About ...

Ways to invoke jQuery(this) within an anchor tag's onclick event handler

My task involves working with HTML code and I need to apply a class name to the parent li tag using jQuery. Here is the HTML code snippet: <ul> <li><a onclick="setSelectedTestPlan();" href="javascript:void(0);">New Test</ ...

`Overlapping navigation against a backdrop of backstretch image`

Is there a way to make the navigation display in front of the background image? Currently, the navigation becomes un-clickable and is hidden behind the image once it loads. ...

The JS content failed to load into the HTML page

I need help creating a workout tracker using two JS files. The main.js file is responsible for loading content from the second file (workoutTracker.js) into the index.html. However, I'm facing an issue where the content is not being displayed on the p ...

From transitioning from a radio button's checked indicator to a complete button

I'm in the process of customizing my WordPress plugin and seem to be struggling with styling the radio buttons. For reference, you can find the code snippet here: https://jsfiddle.net/cd3wagvh/ The goal is to conceal the radio buttons and modify the ...

The page remains static even as the function is executed

Having trouble with creating a sliding form using jQuery. The issue is that instead of sliding to the desired page, it slides to a blank one. The website where this problem can be seen is www.entrilab.com. Upon inspecting the element, there are no errors ...

Is there a way to display a dollar sign either inside or before the input box?

I'm looking for a way to include a "$" sign inside or before the input field where the user enters the hourly pay rate. Any suggestions on how to accomplish this? <tr> <td>Hourly Pay Rate</td> <td><input type = "number" nam ...

Automatically expand all PrimeNG Accordion panels for easy printing purposes

I've implemented the PrimeNG library's accordion component in my angular project. You can find more information here. In my template, I have some custom css styling for printing the page that looks like this: @media print { .profile-progress ...

What is the best way to ensure the alignment of list content and numbering remains separate in HTML while using list-style-position set to inside?

Below is a list with customized styling: ol { background: #ff9999; padding: 20px; list-style-position: inside; } ol li { background: #ffe5e5; padding: 5px; } <ol> <li>Coffee</li> <li>Tea</li> <li>Coca ...

Make the bootstrap button group adjust its size to fit the container dimensions

My goal is to create a display for multiple images with descriptions using a button cycling system. However, I am facing an issue where the buttons overflow the container instead of fitting within it when I wrap the cycler in a container with a fixed width ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

Building a Loading Bar with Two Images Using JavaScript and CSS

I am currently experimenting with creating a progress bar using two images: one in greyscale and the other colored. My goal is to place these two divs next to each other and then adjust their x-position and width dynamically. However, I'm having troub ...

Using jQuery to retrieve child elements and assign numerical values to them

Looking for a jQuery function that can apply different CSS attributes to children elements of a div. <div class="container"> <div class="autogenerated-div"></div> <div class="autogenerated-div"></div> <div class="aut ...

Having difficulty implementing DragControls

My experience with three.js is at a beginner level, and I recently attempted to incorporate a feature allowing the dragging of a 3D model. During this process, I encountered DragControl but faced difficulty implementing it in my code. Upon using new DragCo ...

Unable to identify the source of the additional white space appearing below the footer

Click here to access a page with two Google maps embedded. Upon scrolling to the bottom of the page, an unusual amount of whitespace is visible below the footer that is not seen on any other pages. The issue seems to be related to the presence of the two ...