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

Generating a PDF file from an HTML and CSS page can be done without relying on APIs or libraries, by leveraging the

Is there a way to directly convert an HTML page generated using PHP and CSS into a PDF format without the use of libraries? I have come across multiple libraries that can accomplish this task, but I would prefer not to rely on any external libraries and i ...

What is the best way to customize the appearance of a table using CSS?

I'm attempting to create a table through RAILS that is automatically generated in the default layout. However, I want to customize its appearance using CSS to achieve the desired look. Specifically speaking, from the attached image, I would like the ...

What methods can be used to pause a jQuery function when hovering and resume it when the mouse leaves?

I'm currently working on a jQuery function that operates on the mousemove event. The goal is to have two images - one main image and one shadow image, with the shadow image reflecting movement based on mouse position. While everything is functioning p ...

Guide for verifying the minimum and maximum values when selecting a particular product from a dropdown menu

My goal is to implement validation for the width textbox when a user selects a specific product from the dropdown menu. The validation should only allow the user to enter a value between 10 and 200. I have successfully retrieved the selected value, but I ...

Troubleshooting problem with printing iframes on Firefox

When attempting to print an iframe with a large amount of data using the code below, I'm encountering an issue in Firefox where only the first page is printed. The rest of the pages are not being included in the printout. window.frames[frameID]. ...

Automatically numbering table columns with custom language localization in JavaScript using Jquery

Is there a method to automatically number table data in a local or custom language? As a Bengali individual, I have figured out how to automatically number the first data of each row using css and js. However, I am uncertain about how to implement custom n ...

I'm having trouble getting CSS to apply to my HTML file. Any idea why?

I conducted tests in both Chrome and Firefox, ruling out any browser-related issues. My CSS has been validated and is error-free. However, when I validate my HTML code, an error message pops up stating "Bad value “stylesheet” for attribute rel on eleme ...

Executing a function when a webpage loads in Javascript

I have created a responsive website using Twitter Bootstrap. On my site, I have a video displayed in a modal that automatically plays when a button is clicked. Instead of triggering the function with a button click, I want the function to be called when ...

Increasing the value of a TypeScript variable using ngFor in an HTML template can enhance its usefulness

Can you dynamically increase a variable declared in your TypeScript file for each element generated by an ngFor loop in your HTML file? <tbody> <tr *ngFor="let item of invoiceItems"> <td>{{item.ItemName}}</td> <td>{ ...

Issues with link behavior when using Angular UI-Router

I am just starting to learn AngularJS and I'm trying to figure out how to pass a parameter using anchor tags within the $stateProvider code. I've been attempting to do so, but it doesn't seem to be working. Can someone guide me on the correc ...

By default, the sidebar is open on desktop devices while closed on mobile devices

I am struggling to figure out how to set my sidebar/navigation content, using Bootstrap, to be expanded by default on desktop and closed by default on mobile with the icon only showing on mobile devices. Despite multiple attempts, I cannot seem to make thi ...

Incorporate pug and sass into your React project for a more

Are pug/jade and sass compatible with react? I enjoy organizing my code by separating files, and the functionality that sass and pug provide is great for this purpose. Is there a way to integrate pug and sass into a react project? Pug example: doctype ...

The locator for the span class cannot be found or interacted with in Selenium

Here is the HTML code snippet for a span element: <td class="header-logout-btn"> <a href="logout.htm" class="btn switch-btn"> <i class="fa fa-times"></i><span class="hidden-xs">Home</span> </a> </td> I ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

displaying a pair of inputs next to each other

Is it possible to display two input fields side by side? I am using Angular's matInput forms, but struggling to position the second input next to the first. What I would like to achieve is to have "input1 , input2" on the same line. Here is my code: ...

Two boxes each taking up half of the width, with content placed inside a container

How can I achieve the appearance seen in this image? The layout consists of four columns using regular Bootstrap code. The first two columns should have a white background within a .container, while the other two columns should have a black background tha ...

Styling the content area to fill the entire window in CSS will

<div id="content"> </div> #content{ height:100%; z-index:2; position:relative; top:40px } The content within this DIV is positioned 40px from the top of the page and will scroll under a navigation bar that is 40px high. I am trying to figur ...

Facing Challenges with Python Selenium while Accessing Specific Form Elements in Salesforce

Recently, I've been using Selenium to automate some data entry tasks on Salesforce. So far, my script successfully loads the webpage, allows me to log in, and clicks an "edit" button. Now, I'm encountering an issue when trying to input data into ...

Conceal or reveal radio buttons according to information in a table

How can I dynamically add and remove values from a table based on radio button selections? My goal is to add the selected value to the table and hide it from the radio button list, and if the value is deleted from the table, I want to show it back in the r ...

Can we define a style or CSS for one element depending on the characteristics of another element?

One challenge I'm facing involves a 3rd party library (fullcalendar) that automatically sets the height of elements based on internal calculations to ensure they look good in any viewport: <div style="height: 72px;"> Unfortunately, not all ele ...