Is it possible to overlay a vertical middle on top of an image with an undefined height?

I've been struggling to make this work for the last 24 hours. Initially, I got it working in Chrome using CSS tricks' block:before method, but then realized it didn't function properly in Firefox.

I attempted the table method as an alternative, but encountered issues with achieving 100% height.

The main goal is to position a title in the middle of each masonry brick.

Edit: My objective is to center the <p> tag in the middle of the image. The images vary in height but have a consistent width of 200px.

<div class="item">
<p><?php the_title(); ?></p>
<img src="<?php echo $url; ?>"  />
</div>

Edit: I want the text to be centered on the Overlay element. The <p> tag has a height of 1.5em and dynamic length, which should be handled with overflow auto. The overlay element sits absolutely over the img, which can vary in height but is always 200px wide.

<div class="item>
<div class="overlay" style="overflow:hidden; height:100%; width:100%; position:absolute;">
<p>the title</p>
</div>
<img src="<?php echo $url; ?>"  />
</div>

Your assistance would be greatly appreciated.

Answer №1

Consider this example markup:

<div class="item">
    <p><?php the_title(); ?></p>
    <img src="<?php echo $url; ?>" />
</div>

If you prefer using pure CSS, you can absolutely position the <p> element within the parent container .item. This method assumes that the .item element has a set width, which is usually the case when using jQuery masonry.

To center the <p> element, set its top and left to 50% and then use CSS3 transform to offset it by half of its own dimensions:

.item {
    position: relative;
    width: 300px;
}
.item > p {
    background-color: rgba(0,0,0,.5);
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
.item > img {
    display: block;
    width: 100%;
}

http://jsfiddle.net/teddyrised/e3pFy/3/


The downside of this pure CSS approach is the need for vendor prefixes and lack of support in older browsers like IE8. For compatibility with older browsers, a JS solution using jQuery can be implemented:

$(function() {
    $(".item > p").each(function() {
        $(this).css({
            "margin-left": $(this).outerWidth() * -0.5,
            "margin-top": $(this).outerHeight() * -0.5
        });
    });
});

Instead of using CSS transform, this script calculates and sets negative margins equal to half the dimensions of the element.

http://jsfiddle.net/teddyrised/e3pFy/4/

A drawback of this method is the need to monitor events that may impact page layout, such as viewport resizing, which can lead to complex and bulky code.

Answer №2

In case you have a 'p' element with defined dimensions, here's a simple way to handle it:

.item
{
    width:300px;
    position:relative;
}
p
{
    position:absolute;
    height:1.5em;
    margin-top:-.75em;
    top:50%;
}

(Feel free to explore other methods shared in the link, based on your current or future layout needs)

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

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

IE9 fails to display li::before element correctly

I have created a utility navigation bar using an unordered list and I am attempting to use li::before to add a pipe "|" symbol between each link in the navigation. Below is my utility navigation... <div class="horizontalnavlinks"> <ul> ...

Centering the logo using Material-UI's alignment feature

Need help centering a logo in my login form using Material-UI. Everything else is centered except for the logo, which is stuck to the left side of the card. I've tried adding align="center" and justify="center" under the img tag, but it's still ...

Conceal content within a bullet point

I'm encountering an issue with this specific element. HTML <div class="navbar slide-menu"> <div class="container"> <ul class="nav navbar-default"> <li class="brand"><a href="#">Menu</a></li> ...

Is there a way to position images alongside input fields using Bootstrap?

Struggling to design a user login page for my webapp, specifically getting the username image and input to display next to each other. It used to work fine, but now they won't align properly. I know it's a mess, anyone spot the issue here? I&apo ...

The form continues to submit even if the validation process fails

I am facing an issue where my form still submits to the controller even if the validation fails. Here's my jQuery code: $(document).ready(function () { $('#commentForm').validate(); }); $(function () { $('#commentForm&ap ...

centered calculation with an offset

Check out what I'm attempting here I am trying to keep an element in the center and have another element hug the left side of it. Essentially, I want the leftmost position of the left div to be right: calc(50% - 200px - (left's width)); The is ...

Problems with IE8 - Rendering correctly on all other browsers

I'm having some trouble with my website's display in IE8. It looks great in IE9, Firefox, and Chrome, but in IE8 it appears all jacked up. I'm using WordPress with Thesis Themes and editing custom.css for my changes. You can view my site he ...

How to utilize the CSS hover feature within an Angular directive?

Presented here is the default directive. import { Directive, Input, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[newBox]' }) export class BoxDirective { @Input() backgroundColor = '#fff'; con ...

Tracking User Visits in Codeigniter

Below is the code breakdown: (Step by step) Place counter.txt in APPPATH . 'logs/counter.txt' Set up counter_helper.php in APPPATH . 'helpers/counter_helper.php'; Autoload the newly created helper in APPPATH . 'config/autoload.p ...

Toggle the menu using jQuery on unordered list items

Below is the HTML code I am using : <ul class="main-block"> <li class="firstLevel"> <a href="#category">EXAMPLE CATEGORY 1</a> <ul class="dijete"> <li class="child"> <a href="some-sub-categ ...

The CSS property overflow:hidden or overflow:scroll is not functioning as expected when applied to a

On my practice website, I have set up a demonstration for showcasing text data. The issue arises when the user inserts an excessive amount of characters in the text box. To address this, I would like the text to be scrollable so that all content can be d ...

Stretching the limits: Combining and expanding your Styled Components theme

I am facing a situation where I have a component library built using Styled Components that has its own theme settings which are not meant to be overridden. Now, I need to incorporate this component library into another project that also uses Style Compone ...

The footer should remain at the bottom of the page without being permanently fixed

Is there a way to keep the bootstrap footer at the bottom without fixing it in place? In the code example below, the footer should always appear at the bottom. The white space after the footer should come before it. Using sticky-bottom achieves this, but ...

Autocomplete feature enhanced with the ability to validate and clear out

Here's a snippet of my HTML code: <div class="form-group"> <label for="date_chargement" class="col-sm-4 control-label">Minimum loading date:</label> <div class="col-sm-2"> <input type="text" class="form-control te ...

Incorporating an additional table dynamically based on height considerations – can you provide visuals as guidance?

The visual representation of my question far surpasses my verbal explanation. My intention is to insert a new table once the height of the previous table exceeds a specific HEIGHT limit, not a certain number of rows. This project does not involve creat ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

Activate a tooltip on the button depending on the value entered in the search field

I need to display a tooltip on the button when the search field is empty. Here is what I have attempted: // Enable hover feature const searchBtn = document.querySelector('.find__btn'); searchBtn.addEventListener('mouseover', () => ...

Updating an element within a for loop using Angular TypeScript

I'm trying to figure out how to update the value of an HTML DOM element that is bound from a TypeScript file in each iteration of a for loop, rather than at the end of the loop. I want to see all values as the loop is running. For example, imagine I ...

What could be causing the video not to display in landscape mode on the iPad Pro?

I'm having an issue with a standard HTML5 <video> on my website. The videos are working fine on most devices, however there is a problem specifically with the iPad Pro in landscape orientation. It seems to work properly in portrait orientation ...