What is the best way to center text vertically within an image?

How can I vertically align a blog entry title on an entry thumbnail image? The image size changes with the window size and the title varies in length for each entry.

After finding a website that successfully achieved this effect, I tried replicating it using the code below, but it didn't work as expected.

Check out the example of what I'm trying to achieve at

This is the code snippet I've worked on so far:

http://codepen.io/anon/pen/kFwAH

HTML

<html lang="ja">
      <head>
      </head>
  <body>

    <div class="articleTitle">
    <h1 class="title"><span>Article title. Artile title. Article Title.Article title.</span></h1>
    <img src="http://placeimg.com/500/500/any" alt="">
    </div>

    </body>
</html>

CSS

.articleTitle {

background: #eee;
position: relative;
}

img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
z-index: 1;
max-width:100%;
}

h1 {
line-height: 1;
z-index: 2;
position: relative;
height: 100%;
text-align: center;
vertical-align: middle;
}

h1:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
h1 span {
display: inline-block;
vertical-align: middle;
}

If you have any suggestions or solutions, please help me out. I'm new to CSS and eager to learn.

Thank you!

Note

  • The image size adjusts based on the window size.
  • The entry title can span more than two lines depending on the article content.
  • Compatibility with IE8 is required.
  • I prefer using the <img> tag instead of treating the image as a background of a div.

Answer №1

Revamp your website's look with this updated CSS:

.articleTitle {
  position: relative;
  width:400px; 
  height:400px;
}

img {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  z-index: -1;
  max-width:100%;
}

h1 {
  line-height: 1;
  z-index: 2;
  position: relative;
  text-align: center;
  transform: translateY(-50%);
  -webkit-transform:translateY(-50%);
  top:50%; 
  background:rgba(255,255,255,0.5)
}

You can see the effect with a semi-transparent background here on Codepen.

Answer №2

If you're looking for a simple way to achieve this in newer browsers, check out this link: http://codepen.io/pageaffairs/pen/qCpse

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8>
<style>

.articleTitle {
    display: table;
    position: relative;
    width: 50%; /* adjust as needed, or remove for default image width */
}

.articleTitle {
    display: table;
    position: relative;
}

h1 {
    margin: 0; 
    text-align: center;
}

span {
    position: absolute; 
    top: 50%; 
    left: 0; 
    right: 0; 
    display: inline-block;
    -webkit-transform:translate(0, -50%);
    -moz-transform:translate(0, -50%);
    -ms-transform:translate(0, -50%);
    -o-transform:translate(0, -50%);
    transform:translate(0, -50%);
}

img {
    display: block; 
    width: 100%;
}
</style>
</head>
<body>

<div class="articleTitle">
    <h1 class="title">
        <span>Article Title. Artile title. Article Title.Article title.</span>
        <img src="http://placeimg.com/500/500/any" alt="">
    </h1>
</div>

</body>
</html>

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

Menu elements should display a responsive behavior where on mobile devices, only the icon is shown instead of the word "menu"

Due to the length of our company logo, we need a way to hide certain letters in the Menu and Basket sections, while still displaying the icons. Wrapping the names in span tags and using visibility:hidden; works but leaves empty space visible on the right s ...

Unable to interact with a button element of type="button" using Selenium, but successful with elements of type

In my attempt to interact with the webpage, I am specifically focusing on this button: <button class="button-text-like marg-l-0 float-l desktop-only remove-button" data-bind="click: $root.removeCartItem" type="button"> <i class="gicon-cross">& ...

An error has occurred: sendEmail function is not defined

There seems to be a simple issue here that needs my attention before diving into PHP tasks. I plan on using PHPMailer this time around. I've been attempting to learn how to submit a form on localhost for the past week, and now I'm going to try i ...

Using Javascript to select a radio button in a form depending on the value entered in a text box

I have a form that interacts with a Google Sheet to insert and retrieve data. For instance, the form contains two radio buttons: <input id="Rdio_1" name="RdioSelect" type="radio" class="FirstCheck" value="1" onchange="RadioValInsert ()"/> < ...

Discovering the current page using ons-navigator in Onsen UI

I am currently attempting to determine the page I am on while using the popPage() function with Onsen UI's ons-navigator. I have tried the following methods, but they always return false regardless: this.navigator.nativeElement.popPage().then((page: a ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Incorporating rounded corners to an embedded YouTube video

Check out this JSFiddle link. The border-radius property appears to be working correctly at first, but then the rounded corners suddenly disappear shortly after loading. Is there a way to apply rounded corners to YouTube videos that are embedded on a webp ...

Tips for combining HTML and JavaScript on a WordPress site

As a WordPress developer who is still learning the ropes, I have come across a challenge with embedding html and JavaScript onto a page. Currently, I am in the process of redesigning a company website and one of the tasks involves integrating a calculator ...

Switching minimum and maximum input values based on a specific condition: A step-by-step guide

I am looking for a way to reverse the minimum and maximum values of two input elements that I have defined. Is there a way to achieve this using HTML or JavaScript (Angular)? Here is an example of what I am trying to do: <label> Width: < ...

What are the steps to modify the "text" displayed on a button in a kendo grid?

How can I change the default button text "add new record" on my kendo grid? I attempted to modify it using the following code, but it did not work: #turbinegrid .k-icon.k-add::after { content: "ADD"; } ...

The production build encountered an issue as it was anticipating 3 arguments, however, it only received

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'elipsis' }) export class ElipsisPipe implements PipeTransform { transform(text, length, clamp) { text = text || ''; clamp = clamp || '...& ...

What is the proper placement for index.html <head/> class helper functions within a ReactJS Component?

My custom helper functions are stored in a JavaScript file called classie.js: ( function( window ) { 'use strict'; function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, ...

Tips for creating a filter that meets multiple conditions in HTML

Click here for image descriptionI have the following code where I am utilizing story owner and story state. ng-repeat="item in IterationStories | filter: {Story: {storyOwner: filterRequestor}} | filter: {Story: {state: filterKey}} " //works fine when ...

Can someone explain why line-height can affect the width in CSS?

Can you explain how the line-height property functions in CSS? I have noticed that when I set the line-height to be equal or less than the font size, it causes layout width issues. You can view an example of this problem on a jsFiddle here. Currently, my ...

Utilize the get method to showcase data in a material UI table for a React application

Just starting out with React. Managed to create a table component with hard-coded data. However, I now have all the data stored in table.json. Can someone guide me on how to fetch values from table.json using an axios get request an ...

Embed an HTML element within a DIV container

How can I add an HTML tag such as <p> to wrap around the text "Search"? <button id="ihf-quicksearch-submit2" class="btn btn-lg btn-block btn-primary btn-form-submit ihf-main-search-form-submit" type="submit"> Search </button> I am looki ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Eliminate any iframes that have a src attribute with the value of "some_src.com/....."

I'm brand new to coding in javascript. I've noticed that there is an annoying ad popup that manages to sneak through Adblock super without being detected. It's driving me crazy and I want to block it! Here's the code for the iframe: IF ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

Hide the cursor when the text box is in focus

Is there a way to remove the cursor from a textbox when it is clicked on? I want the cursor to disappear after clicking on the textbox. jQuery(document).ready(function($) { $(function(){ $('#edit-field-date-value-value-datepicker-popup-0&ap ...