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

"Step-by-Step Guide to Dividing and Centering Text Sections with Dynamic

Initially, my intention is to implement the concept outlined below. The webpage has dual potential states. In the first scenario, two texts (with potentially varying lengths) are centralized together as a header. When transitioning to the second state, the ...

Is it possible to use JQuery to trigger a click event on text inside

Trying to implement a JQuery method that triggers when the code below is clicked: <div class="content_sub_list"> <img src="/imgs/close-icon.jpg" class="exit_sub_list"/> hello </div> The current JQuery code in use: $(document).r ...

What is the process for importing a local widget file in Angular?

I have a unique widget named employee-widget stored in the Angular application folder as employee-widget.js. Despite following the calling method below, the widget fails to load. Method 1: <div> <h4>Attempting to load the employee widget& ...

"Which is better for maximizing the efficiency of an image grid: CSS or Jquery? What are the key

As a UX Designer looking to enhance my coding skills, I must admit my code may not be perfect. Please bear with me as I navigate through this process. I am in the process of revamping my portfolio website. The original seamless grid was created using a Ma ...

What is the best way to include the application version in an Electron project using JavaScript

While attempting to publish an update for my app, I encountered a strange error. Can anyone pinpoint the issue? (Note: Node.js is included) Error Message: Unexpected token < <script> console.log(process); let output = <h2 class="page- ...

Experiencing a problem with XAMPP? Changes made to the code are not reflected after saving

Recently, I've encountered a strange issue with my XAMPP test server while working on a game project. Everything was running smoothly until I noticed that when I make changes to certain files in Notepad++ and save them, the updates are not being refle ...

Tips for preventing delays in the digest cycle caused by two-way binding

When does two way data binding get triggered in AngularJS? In my AngularJS application, there is a parent directive and a child directive. Parent Directive: angular .module('myApp') .directive('customForm', function(customService ...

The grid expands to cover the entire width of the browser

Hello everyone, I am a newbie when it comes to JavaScript and CSS. I am in need of a code, whether it be JavaScript or CSS, that will allow me to stretch out a grid layout measuring 5 x 2 along with pictures to completely cover the width of the browser wi ...

Best practices for refreshing the HTML5 offline application cache

My website utilizes offline caching, and I have set up the following event handler to manage updates: applicationCache.addEventListener('updateready', function () { if (window.applicationCache.status == window.applicationCach ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

I found it challenging to select a particular choice using Selenium in Python

My goal is to use Selenium and Python to select the "Yazar" option within this particular HTML tag. However, I have encountered a problem where I am unable to successfully click and choose the "Yazar" option. Can anyone provide guidance on how to achieve t ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

I created a customized version of jQuery tabs, but I am looking for an external link to display the tab content and to style the original navigation

I've been experimenting with modifying a tabs script in jQuery that I came across. It seems like my attempt to enhance it has made things more complex than necessary. While I know creating tabs with jQuery is simple, I wanted to create my own version ...

Avoiding the inclusion of special characters in symfony css selectors, or utilizing wildcard characters for more

Currently, I am utilizing the Symfony\Component\DomCrawler\Crawler component in order to locate a form that contains a name with various CSS special characters. <input name="myfield[0].thing"> In my code, I have: $messageElement = $ ...

Attempting to iterate through an array of HTML5 videos

Having some trouble with my video array - it plays but doesn't loop. I've tried using the HTML video attribute 'loop' and variations like loop="true" and loop="loop" without success. Tonight, all I want is for it to loop properly! var ...

The issue with the $(window).width() property not functioning correctly in Internet Explorer

Currently, I have a Div element with absolute positioning: <div id="target" style="height: 300px; position: absolute; top: 275px;"></div> My goal is to calculate the horizontal resolution of the screen using JavaScript. With this width, I the ...

What is the best way to insert a block of text above a slideshow without causing it to move downwards?

I've successfully integrated a slideshow within a section tag using a div tag. To include text above the slideshow, I placed another div tag above the slideshow div. However, when adding more text, it causes the images in the slideshow to get pushed d ...

css: centrally align a collection of items that are spaced evenly throughout the group

I have multiple divs inside a container that I want to evenly distribute horizontally: [container [obj1] [obj2] [obj3] [obj4] ] Additionally, I would like the container to be centered on the page My current CSS (stylus) code for the container is as foll ...

What is the best way to make an image clickable in Next.Js?

Is there a way to turn an image into a link in Next.Js? I have the Instagram logo that I want to use as a link to my Instagram page. I want it to open a new tab and redirect the user to my Instagram account when clicked. I would really appreciate any guid ...