How to align text to the bottom of a div using CSS

I am struggling to position the text 'About' at the bottom of an image. The red line marks the spot where I want the text aligned at the bottom. However, every method I try results in inconsistent outcomes when viewed on desktop and mobile devices. It currently displays correctly on my laptop, you can view it here (click the image to see the slide.)

This is what the HTML looks like: (hosted on GitHub using liquid tags)

<div class="slide_title">
    <span>{{ include.title }}</span>
</div>

<div class="slide_heading clickable">
    <img src="{{ include.image }}" width="100%" alt="{{ include.title }}"/>
</div>

The CSS:

.slide .slide_title {
    font-size: 4.938em;
    color: #f8f8f8;
    font-weight: bold;
    font-family: Arial, Helvetica, sans-serif;
    margin: 0;

    pointer-events:none;

    position: absolute;
    left: 0.000em;
    top: 14.188em; /*default when no JavaScript is used, otherwise set in JS*/
}

.slide .slide_title span {
    position: absolute;
    bottom: -0.24em;

    white-space: nowrap;

    text-shadow: 0 0 0.05em #999999;
}

The text is within a div, styled with position: absolute, and positioned alongside my image (so the bottom of the div aligns correctly with the bottom of the image). Now I am trying to accurately position the text within the div.

Everything I have attempted has yielded inconsistent results. While it appears correctly on my desktop, there is a different offset on mobile devices.

Methods I have tried (to the best of my recollection):

  • I attempted giving the div a fixed offset in my script for positioning.
  • Adjusting the height of the div, which moved the text as desired.
  • Placing the text in a span inside the div and adjusting the span by setting its bottom property. This is the current method, and is the closest I have come to achieving consistent alignment across all platforms.

I also experimented with setting the vertical-align of the div to bottom, but the text did not shift at all.

Is there a reliable way to align text in this manner that will work universally?

Thank you!

Note: JQuery is being used to position the div.

Answer №1

The crucial point to grasp here is the nature of your task:

  • you are requesting for the baseline of the font to align with the bottom of the parent container,
  • it's important to note that, in your image, the text within the div is correctly positioned

To achieve your objective, you can adjust the font-size and line-height, while utilizing either position: absolute; or position: relative;.

font-size

Your image depicts the text being at or nearly at the bottom of the parent div. This positioning discrepancy is due to the fact that an element's font-size accounts for both ascenders and descenders. You can observe this by changing the text to something like "Apropos," revealing the additional spacing for letters like g, j, p, q, and y.

line-height

Another factor at play is most likely the line-height setting exceeding 1. This can be confirmed by inspecting the element to check if the height (excluding padding, borders, and margins) surpasses the font size.

You can enforce uniform line heights by setting line-height: 1;, although beware that this may cause word overlap in multi-line scenarios.

Mobile -vs- desktop

The issue of desktop versus mobile differences remains unresolved. With a comprehensive understanding of font-size and line-height, you should be able to:

  • accurately position the text so that the bottom of the text element aligns with the parent element's bottom edge, and
  • utilize position: absolute; or position: relative; for precise adjustments

If inconsistency persists across devices, it is likely attributed to varying font sizes on different devices. This could result from various factors such as:

  • distinct base font sizes on mobile devices compared to desktop browsers, impacting em-based sizing used for alignment
  • CSS frameworks potentially adjusting font sizes for smaller screens

Implementing a combination of media queries and pixel dimensions could resolve this issue.

Consider trying the following approach, and if results remain unsatisfactory, proceed to customize media queries to address any discrepancies:

.slide-title {
  /* Enter your desired pixel values here */
  bottom: -3px;
  font-size: 16px;
  line-height: 1;
  position: absolute;
}

While pixel sizes are viable options, there is no inherent drawback given enhanced scalability features. However, if using ems is essential, initially testing with pixels before transitioning to ems can streamline troubleshooting. Identifying what differs in the cascade between pixel and em declarations will be pivotal if the latter proves more problematic.

Answer №2

Consider trying the following code snippet:

<div class='container_wrapper'>
   <div class="container_title">
       <span>{{ include.title }}</span>
   </div>

   <div class="container_content clickable">
       <img src="{{ include.image }}" width="100%" alt="{{ include.title }}"/>
   </div>
</div>

Here is the corresponding CSS:

.container_wrapper {
   position: relative;
}

.container_title {
   position: absolute;
   top: 0;
   left: 0;
   z-index: 2;
}
.container_content {
   position: absolute;
   top: 0;
   left: 0;
   z-index: 1;
}

To update dimensions with jQuery:

var w = $("container_content").width();
var h = $("container_content").height();
$(".container_wrapper").css({width: w, height: h});
$(".container_title").css({width: w, height: h, line-height: (h - 20px)});

Please note that this code has not been tested extensively, but it should function correctly. Adjust the [b]20px[/b] value according to the distance of the red-line from the bottom of the image.

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

How can I create a unique visual effect on the background in frontend development using chipped design techniques?

Creating a static website utilizing React. Description I am looking to incorporate a visual effect into the website pages, similar to the one demonstrated below. visual effect The goal is to design a rectangular background with triangles cut out from it ...

The Jquery delete button is efficiently targeting and removing all image sources and identifiers within a Multiple Upload feature

I need help creating a delete button for my ImageUploader. I can successfully select an image and display it in a div on my page, but deleting the current image is proving to be challenging. When I click on the delete button, instead of getting the id and ...

Displaying an array value instead of a new value list in a React component

Situation - Initial number input in text field - 1 List of Items - 1 6 11 Upon removing 1 from the text field, the list becomes - New List Items - NaN NaN NaN Now, if you input 4 in the field. The updated List Items are - NaN NaN 4 9 14 Expected ...

Creating an overlay effect when hovering over an image

Recently, I've been working on a gallery of photos that showcases different individuals. My goal is to have information about each person displayed when their respective photo is hovered over - including their name and role. .gallery { position: ...

Retrieving specific data from an SQL database using PHP

My goal is to create a select form with fields populated from an SQL database containing a table of stores. I used a method to retrieve distinct store names and populate the select tool with them. echo '<select name="StoreName" />'."\ ...

What is the best way to identify which JavaScript code is triggering or managing an event?

In the development of an HTML5 application framework designed for businesses to use on their intranet and extranet sites, a SAP JEE application server is utilized. The framework incorporates the grid system known as "Semantic UI" along with various JavaScr ...

Experience the innovative feature of React Splide Carousel where a peek of the next image is shown until you reach

My current challenge arises when I reach the last slide in the slider. I am trying to prevent it from looping and instead stop with no extra space or any other images peeking out. To address this, I have utilized the padding: '5%' option, which ...

JavaScript Function Not Executed in Bottom Section

I've implemented AngularJS includes in my project. Below is the code snippet from my index.html: <!DOCTYPE html> <html ng-app=""> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> ...

Various settings in JQuery UI Slider

Does anyone know how to customize the steps in a jQuery UI slider? I want to set specific values as steps, like 0, 1200, 2000, 2200, and 3000. Any suggestions on how to achieve this? const rangeSliderInit = () => { const valueArray = [0, 400, 1000, 1 ...

Inject a dynamic URL parameter into an iframe without the need for server-side scripting

I'm really stuck and could use some assistance with the following issue, as I am unable to solve it on my own :( When a user is redirected to a form (provided via an iframe), there is a dynamic URL involved: website.com/form?id=123 The code resp ...

Vue JS: Extracting both the unique ID and value from an array of input simultaneously

I am new to Vue and currently exploring its capabilities. I am experimenting with the Element UI for Vue's user interface. Specifically, I am working with the Input Number Component, to manage an array of data. Let's assume my data is structured ...

jQuery fails to modify HTML according to its intended purpose

I've been struggling to update a price using JQuery. Even though the code seems fine when I check the console, the HTML doesn't reflect the changes. Additionally, when I try to log console.log(newPrc), it gives an error saying "newPrc" is not def ...

AngularJS combined with jVectorMap allows for the seamless rendering of small interactive

I am facing a similar issue to one discussed here, but with some minor differences. Initially, my map loaded without any problem on the site. However, after adding Angularjs to the site, I noticed a 'small' map issue. It seems like a simple code ...

Modify the hue of the iron-icon upon being tapped

There's a simple example I have where my goal is to modify the color of an iron-icon when it's tapped. To achieve this, I'm utilizing iron-selector for tapping: <template> <style> :host { display: block; padding: 10 ...

Markdown in Vue.js filters

I found a helpful example by Evan You on how to convert HTML to markdown - check it out here. However, when trying to install the marked package via npm and implementing it, I encountered an error stating that 'marked' is not defined. After inc ...

What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button: <input class="close-acc-usr opt-in" type="text" name="closeAccUsr" /> <input class="close-acc-pin opt-in" type="number" name="cl ...

Is there a way to adjust the speed of the transitions between animations?

I've been experimenting with ways to increase the time between animations in my cycle. Adjusting the duration of the keyframes animation hasn't yielded the desired effect. span { animation: rotateWordsFirst 15s linear infinite 0s; ...

I am experiencing an issue with the interaction between my "label" tag and "summary" tag. The details are not opening when I click on the label. Can someone please provide guidance on how to resolve this

I have reviewed the question here, but it does not provide an answer, and there's also this related question. However, my question has a slightly different angle. I am encountering an issue where adding another element inside the summary tag prevents ...

Guide to changing the border color in a Material-UI TextField component styled with an outline design

To complete the task, utilize the Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and apply a custom blue color style to it. Here is the outcome of my work: Current theme override for InputL ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...