Align the heading vertically when the div is set to position:absolute

I'm looking to center the heading text vertically within the div, but currently it is being pushed down with margin-top which is causing issues when the titles spill over onto a second line.

For reference, please check out the example here:

HTML

    <div id="page-featured" style="background: url(<?php echo $src[0]; ?> ) !important; overflow: hidden; background-size: cover !important; background-position: center !important;"></div>

    <div id="page-overlay">
        <div id="page-titles">
            <h1><?php the_title(); ?></h1>
        </div>
    </div>

CSS

#page-overlay, #page-featured {
    height: 400px;
    width: 100%;
}

#page-overlay {
    position: absolute;
    top: 95px;
    background-color: rgba(0,0,0,0.1);
    z-index: 100;
    color: #FFF;
}

#page-titles {
    width: 100%;
    height: 100%;
    text-align: center;
}

#page-titles h1,
#page-titles p {
    margin: 0px;
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
}

Appreciate your help!

Answer №1

To align vertically, you can utilize the CSS3 property transform: translate

To learn more, visit:

CSS

#page-overlay, #page-featured {
    height: 400px;
    width: 100%;
}
#page-overlay {
    position: absolute;
    top: 95px;
    background-color: rgba(0, 0, 0, 0.1);
    z-index: 100;
    color: #FFF;
}
#page-titles {
    width: 100%;
    height: 100%;
    text-align: center;
    position: relative;
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;
}
#page-titles h1, #page-titles p {
    margin: 0px;
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    text-align: center;
    width: 100%;
}

VIEW DEMO

Answer №2

To easily center an element without knowing its container's height, you can utilize absolute positioning and negative margins. Adjust the top value of #page-titles h1 to 50%, then subtract half of the element's height from the margin-top property (e.g. margin-top: -24px). Check out this demonstration on a fiddle: http://jsfiddle.net/8s1g7ws0/. This method also works for horizontal centering.

The concept here is that setting top: 50% places the element's starting point in the middle of its container, not truly centering it. By moving it half of its height upwards, we align both elements' midpoints.

If you're unsure of the element's height, consider changing the container to table-cell display and use vertical-align: middle to center its contents. In your scenario, follow these steps:

  • Include display: table in #page-overlay
  • Delete position: absolute from #page-titles h1
  • Apply display: table-cell and vertical-align: middle to #page-titles

Check browser support for display: table here.

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

Certain parts of the CSS grid are not aligning properly within the grid lines

I'm having trouble with my CSS grid. The red section fits in the first square, but the rest of the content seems to be out of place in the grid. I'm new to all this and I can't figure out what I'm missing. I've tried everything but ...

Tips on preventing a nested loop's inner ng-repeat from updating when the array undergoes changes

My current challenge involves working with an array of events, each event has teams participating in it. Although these objects are related, they are not properties of each other. I am attempting to loop through every event and display the teams participa ...

What is the best way to customize the lower border color of a collapsed Bootstrap navbar with an inverse design

Discussing this issue.. I am noticing two distinct colors. One is darker than the background shade and the other is lighter than the background shade. How can these be set? https://i.sstatic.net/Y39IZ.jpg <nav class="navbar navbar-inverse"> <d ...

Align image within box using Bootstrap

My project screenshot is displayed below. The red line separates the current state from the desired outcome. I am struggling to make it fullscreen, meaning it should extend all the way to the corners. Despite trying various methods with Bootstrap 4, I have ...

The Bootstrap column is causing a cropping issue on the left side of my rows

I'm currently working on a Python/Flask/HTML project that utilizes Bootstrap 4 for a grid system with multiple rows and columns. However, when I attempt to run the project, a few pixels get cut off on the left side of the screen. I've thoroughly ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

Issue with Flask form submission in a specific scenario but functioning correctly in a different context

I'm currently working on a flask website, and I'm facing an issue with the SubmitField not functioning when I click it. I tried a similar method with a smaller form and it worked, but for this specific case, it's not working. routes.py from ...

Issues with ng-click functionality not activating on <li> HTML elements

I've been attempting to add ng-click functionality to my list, but it's not working as expected. I've tried adding the ng-repeat directive and also without it on li elements. Here is the snippet of HTML code: <ul class="nav nav-tabs"&g ...

HTML & CSS: Modify background rectangle behind text to limit its size within the webpage dimensions

I'm experiencing a unique issue with the current code present in my HTML index file. <div class="titleMessage"> <div class="heading"> <p class="main">NAME HERE</p> <p class="sub">Software Engineer& ...

Iterate through three images using the `background-image` property in my Div

Is there a way to modify a code that loops through images based on an Img source in order to work with the "background-image" property of a div? HTML <div id="section2"></div> CSS #section2 { background-image: 'url(..images/banner1.jp ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

Is there a way to automatically redirect the main html page to a different html page upon logging in?

I have created a main page in HTML with a login box that displays a message saying "Login successful" or "Login failed" based on whether the password entered is 8 characters or more. The validation function for this works correctly, but after successfully ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Osclass Website Alert: Multiple H1 tag Issue Detected

I operate a website called MyMobPrice and utilize OsClass for its functionality. However, I am encountering an error on each product page stating "More than One H1 Tag found." The issue lies within the two sets of H1 codes designed for desktop and mobile ...

Stop Bootstrap from impacting a specific division on my webpage

Is there a way to stop Bootstrap from impacting a specific div and its nested divs in my HTML document? Since adding Bootstrap, the images inside this particular div have turned dull and acquired an undesirable blue tint. Thank you for considering my conce ...

Retrieve the image information from a specified element in the Document Object Model

Is it possible to extract the image data of a DOM element using standard JavaScript or browser extensions? I'm considering scenarios where: Creating an offscreen DOM element Populating it with dynamically styled CSS content Retrieving its image dat ...

Complete picture in a circular div with aspect ratio

I'm currently working on creating a profile page and I'd like to have an image inside a circular div. The challenge is that I want the image to maintain its aspect ratio, even though the dimensions are unknown and users can upload images of any s ...

Applying scoped CSS styles to parent elements in HTML5

I've been delving into the details of the HTML5 specification, specifically regarding the scoped attribute on style elements. According to the specification: The scoped attribute is a boolean attribute. When used, it signifies that the styles are mean ...

Legend alignment issue in Firefox disrupting Flexbox functionality

My fieldset has a legend containing text and a button. I am attempting to use flexbox to right-align the button within the legend. This setup works correctly in Chrome, but encounters issues in Firefox. I have managed to replicate the problem with a simpl ...

Enhance video playback by eliminating accidental scrolling through the space bar

When using a video player, I always prefer to pause it by pressing the spacebar. However, this function is not working as expected. The issue at hand is that instead of pausing the video, pressing the space bar causes the page to scroll down unexpectedly ...