What is the best way to perfectly center text within an image, maintaining both vertical and horizontal alignment, all while being contained within an <a> tag?

I've been working with this code snippet. When I set the position of .thumb-title to absolute and use bottom: 50%, it shifts upwards in relation to its own height.

.project-thumb {
  position: relative;
}
.thumb-title {
  font: 400 1.5rem 'Lato', sans-serif;
  position: absolute;
  bottom: 50%;
  text-align: center;
}
<li>
  <a class="project-thumb" href="ktc.html">
    <img class="thumb" src="thumbs/thumb-201612t-ktc.jpg">
    <h3 class="thumb-title">Sample text</h3>
  </a>
</li>

Answer №1

When determining the width of the thumb, you can implement display:inline-block;, vertical-align:middle, text-align:center;, and adjust the margin as needed to center the content without relying on absolute or transform.

.project-thumb,
.project-thumb h3 {
  display: inline-block;
  vertical-align: middle;
  position: relative;
  width: 150px;/* thumb's width */
  box-sizing: border-box;/* consider borders or padding*/
  color: initial
}
.thumb {
  vertical-align: middle;
  margin-right: -150px;/* reduce width virtually to align text */
}
.thumb-title {
  z-index: 1;/* ensure it appears above image*/
  text-align: center;
}
<a class="project-thumb" href="ktc.html">
  <img class="thumb" src="http://dummyimage.com/150x150/aaaaaa/aaaaaa&text=."><!-- 
  make sure to maintain white space for inline-block elements
  --><h3 class="thumb-title">
      Sample text</h3>
</a>
 

<a class="project-thumb" href="ktc.html">
  <img class="thumb" src="http://dummyimage.com/150x150/aaaaaa/aaaaaa&text=."><!-- 
  remember to preserve white space for inline-block elements
  --><h3 class="thumb-title">
      Two lines <br/> of text</h3>
</a> 


Edit: It seems you mentioned using a flexbox in another answer. Here is a version with Flexbox, based on your layout and CSS.

.project-thumb,
.project-thumb h3 {
  display: inline-flex;
  position: relative;
  width: 150px;/* thumb's width */
  box-sizing: border-box;/* consider borders or padding*/
  color: initial;
  justify-content:center;
}
.thumb {
  margin-right: -150px;/* reduce width virtually to pull text */
}
.thumb-title {
  z-index: 1;/* ensure it appears above image*/
  margin:auto 0;
}
<a class="project-thumb" href="ktc.html">
  <img class="thumb" src="http://dummyimage.com/150x150/aaaaaa/aaaaaa&text=."><!-- 
  make sure to maintain white space for inline-block elements
  --><h3 class="thumb-title">
      Sample text</h3>
</a>
<a class="project-thumb" href="ktc.html">
  <img class="thumb" src="http://dummyimage.com/150x150/aaaaaa/aaaaaa&text=."><!-- 
  remember to preserve white space for inline-block elements
  --><h3 class="thumb-title">
      Two lines <br/> of text</h3>
</a>

Answer №2

To center-align the content in a .project-thumb, you can use the text-align: center; rule and position the title using the left: 50%; with transform: translate(-50%,-50%); for the .thumb-title element:

.project-thumb {
  position: relative;
  display: inline-block;
  text-align: center;
}
.thumb-title {
  font: 400 1.5rem 'Lato', sans-serif;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  padding: 0;
  margin: 0;
}
<li>
  <a class="project-thumb" href="ktc.html">
    <img class="thumb" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfUCAwWIxZtCx0SAAAAHXRFWHRDb21tZW50AENyZWF0ZWQgd2l0aCBUaGUgR0lNUO9kJW4AAAInSURBVHhe7dXRCcMwEAXBU/rvWXZw4o/gbAUzcEgNLG/NzD4PePD6vMCDe0H2NiTwtdY7DQsCSSAQBAJBIBAEAkEgEAQCQSAQBAJBIBAEAkEgEAQCQSAQBAJBIBAEAkEgEAQCQSAQBAJBIBAEAkEgEAQCQSAQBAJBIBAEAkEgEAQCQSAQBAJBIBAEAk...included)>
    <h3 class="thumb-title">Sample text</h3>
  </a>
</li>

Answer №3

Appreciate the assistance! I did some testing and found a solution that worked for me:

Here's the HTML snippet:

<li>
    <a class="project-thumb" href="ktc.html">
        <img class="thumb-img" src="thumbs/thumb-201612t-ktc.jpg">
        <h3 class="thumb-title">Sample text</h3>
   </a>
</li>

And here is the CSS code:

.thumb-project {
display: inline-block;
position: relative;
}

.thumb-img {
width: 100%;
height: auto;
}

.thumb-title {
font: 400 1.2rem 'Lato', sans-serif;
position: absolute;
width: 100%;
bottom: 50%;
text-align: center;
opacity: 0;
}

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

Modify the image inside a div when hovering

How can I create a product card that displays thumbnails of images when hovered over, and changes the main image to the thumbnail image? My current challenge is getting this functionality to work individually for each card on an e-commerce site. Currently, ...

The canvas texture is not properly aligning with the SphereMesh

I have been experimenting with THREE.js and recently tried using a <canvas> element as a THREE.Texture. After finally successfully mapping the object to the mesh, I noticed that the texture was not wrapping around the SphereGeometry as expected; inst ...

Having trouble retrieving a base64 encoded image from a MySQL database using PHP

Within my MySQL database, there is a longblob field that stores a binary value representing an image uploaded through my website. I am currently attempting to retrieve the image using: <?php while($record = mysqli_fetch_assoc($result)): ?> <div&g ...

Is there a way to access an SD card by clicking on an HTML link using JavaScript?

UPDATE: I am seeking a way to embed an HTML file with JavaScript or jQuery that can directly access the contents of the SD card while being opened in a browser. Currently, I have posted code for accessing it through an activity, but I want to be able to d ...

Tips for making an image box with a rollover effect

I need help figuring out how to create a unique user experience within a container that is 500px wide and 800px tall. The container currently has an image as a background, and I want to add a "sign up" button in the middle. When this button is clicked, I w ...

Adjust the background color of child divs when the parent div is being hovered over

I am facing a challenge with my current setup: <div class="parent"> <div class="child"> </div> <div class="child"> </div> <div class="child"> </div> </div> My goal is to change the background co ...

Exploring jQuery Animation Effects: Enhancing Your Web Experience with Zoom In and Zoom Out

Is there a way to animate a logo using jQuery automatically upon page load? I want the image to zoom out, then zoom in and change to a different image. Can someone please assist me with this task? Below is the code snippet that I have: $(document).ready ...

Achieve full height in Grid component of material UI by eliminating margins

In this codesandbox example, I have successfully set the grid container height to full using 100vh. However, there is an issue with a margin of 8px being added by the user agent to the body element, and I'm struggling to find a solution to remove it. ...

Customizing your buttons in Wordpress with extra CSS styles upon clicking

I am in the process of developing a Wordpress website and I require a button for switching between mobile and desktop versions manually. Within my .css file, I have included: @media (pointer:coarse) {} This adds modifications for the mobile version ...

Retrieving information from an API and presenting it as a name with a link to the website

I am attempting to retrieve information from an API and present it in the format Name + clickable website link. Although I have managed to display the data, the link appears as text instead of a hyperlink. Here is my Ajax script: $(function() { ...

Finding the image source of a clicked image

Is it possible to retrieve the image src after clicking on another image? $(document).ready(function() { $('img.getimage').click(function() { alert($(this).attr('src')); }); }); .sinistra { width: 150px; } .getimage { wi ...

Adjust the Material UI Select component to accommodate the length of the label

Is there a way to automatically adjust the size of Material-UI's Select input based on the label? In the official demo, minWidth is added to the formControl element. However, I have multiple inputs and do not want to set fixed sizes for each one. Whe ...

Crafting visually stunning interfaces with Material UI

I'm a beginner in Material Design and I could use some assistance with the following structure. Can anyone guide me on how to create this? https://i.stack.imgur.com/NpiVz.png I've managed to add a text box, but now I'd like to place a label ...

The functionality of the onclick and onserverclick attributes seem to be malfunctioning when

I am in the process of creating a basic login screen using the code provided below: <form id="login"> <div class="formHeader"> <h1>Login</h1> </div> <div class="formDiv"> <input type="text" placeholder="Email" na ...

Managing iframe scrolling using the parent window's scrollbar

I am currently working on an iframe to be utilized across various domains. The functionality of this iframe involves displaying a data list that updates when the bottom of the scroll is reached. An issue I encountered is that the parent window, where the ...

Ensure that the responsive SVG image remains centered even when resizing

I have been attempting to center crop the responsive SVG image while resizing. Even though I used preserveAspectRatio="xMidYMax slice", the image width does not stay consistent with my screen size. body{ margin:0;padding:0; } .wrapper { position: re ...

What is the best way to ensure that this <span> maintains a consistent width, no matter what content is placed inside

So here's the deal, I've got some dynamically generated html going on where I'm assigning 1-6 scaled svgs as children of a . The span is inline with 2 other spans to give it that nice layout: I want these "boxes" to all be the same width be ...

Retrieve data from an SQL database and populate an HTML dropdown menu in a web page using PHP

I am a beginner in the world of JavaScript and facing some challenges. I am working with PHP 7 and attempting to retrieve data from an SQL database, specifically a table. My goal is to extract a single column from this table and display it in a dropdown me ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Is there a way to incorporate my personalized styling and HTML code into Django forms?

I've been struggling to customize form styling in Django. I want to exclusively use my own styles for the forms. How can I achieve this? <form id="contact" action="" method="post"> <div class="row"> ...