CSS for aligning to baseline grid

Update: I am seeking advice on how to align text to a baseline using different font sizes within a div. Despite my efforts, I have not found a satisfactory solution online. It seems impossible to achieve without the use of a Javascript framework or css preprocessor. This is perplexing considering the known proportion of the font below the baseline.

In the provided code snippet below, changing the font size of .text2 to 22px causes the two text groups to no longer align at the baseline (the bottom of the 'h'). However, reverting it back to 32 px results in proper alignment. Since both fonts are in Arial and the descenders of the 'j' should be proportionate, any insights into why they do not align?

View the code here

CSS:

.bottomalign
{
  position: absolute;
  float: left;
  bottom: -.24em;
}

.container
{
  position: relative;
  height: 50px;
  overflow: visible;
}

div
{
  font-family: arial;
}

.text1
{
  font-size: 16px;
}

.text2
{
  font-size: 32px;
  margin-left: 2px;
  color: green;
}

HTML:

 <div class="container">

      <div class="bottomalign text1">jh</div>
      <div class="bottomalign text2">jh</div>

 </div>

Answer №1

If you're looking to ensure that your divs align properly regardless of size, my recommendation would be to set them with

display: inline-block; vertical-align: baseline;
. This will help maintain the alignment you desire. Check out this link for more details: http://codepen.io/pageaffairs/pen/ucyIt

Alternatively, consider this second option mentioned in the note: http://codepen.io/pageaffairs/pen/jBcxk

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

body {
    font-family: arial;
}

.container div {
    display: inline-block;
    vertical-align: baseline;
}

.text1 {
    font-size: 16px;
}

.text2 {
    font-size: 32px;
    color: green;
    margin-left: 2px;
}

</style>
</head>
<body>

<div class="container">
    <div class="text1">jh</div>
    <div class="text2">JH</div>
</div>

</body>
</html>

Answer №2

The variation in default line-height across browsers is the main reason for the discrepancy: Mozilla typically uses a value around 1.2. To address this issue, the code snippet above required a reset for the line height:

.bottomalign
{
  position: absolute;
  bottom: -.17em; //arial descends 17% below baseline
  line-height: 1;
}

Reference the following link for more information:

Answer №3

If you're seeking a solution that involves dynamic adjustments using JavaScript rather than just CSS, the following code snippet should help:

To make the necessary changes, simply delete the "bottom: -.24em;" declaration from the bottomalign class and insert the provided script tag:

Snippet to be added:

<html>
<head>
<style>
.bottomalign
{
  position: absolute;
  float: left;

}

.container
{
  position: relative;
  height: 50px;
  overflow: visible;
}

div
{
  font-family: arial;
}

.text1
{
  font-size: 16px;
}

.text2
{
  font-size: 32px;
  margin-left: 2px;
  color: green;
}
</style>
</head>
<body>
<div class="container">

      <div class="bottomalign text1">jh</div>
      <div class="bottomalign text2">jh</div>
    <script language="javascript"> document.getElementsByClassName("bottomalign text1")[0].style.top = document.getElementsByClassName("bottomalign text2")

[0].clientHeight - document.getElementsByClassName("bottomalign text1")[0].clientHeight - 1 + 'px'; </script>
 </div>
</body>
</html>

Answer №4

After exploring different options, I have come up with a solution that may align with what you are seeking.

TL:DR; You can check out the code snippet here

To achieve this, I utilized the CSS property display: table-cell;. Below is the CSS I implemented based on your HTML structure:

.bottomalign {
    display: table-cell;
}
.container {
    position: relative;
    height: 50px;
    overflow: visible;
    display: table;
}
div {
    font-family: arial;
}
.text1 {
    font-size: 16px;
}
.text2 {
    font-size: 32px;
    color: green;
}

The container was given a display: table;, while the bottomalign had a display: table-cell;.

Please review and let me know if this meets your requirements.

Answer №5

Implementing this is now possible by utilizing display: flex along with align-self: flex-end:

.container {
    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    height: 24em;
}

.bottom-align {
    -webkit-align-self: flex-end;
    -ms-flex-item-align: end;
    -webkit-align-self: flex-end;
    -ms-align-self: flex-end;
    -o-align-self: flex-end;
    align-self: flex-end;
}

.text-1 {
    font-size: 1em;
}

.text-2 {
    font-size: 2em;
}

I have made enhancements to your initial approach, view it here.

Please bear in mind that the flexbox specification is continuously evolving, requiring the inclusion of prefixes presently, unless a tool such as autoprefixer is employed.

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

Best method to generate an element using any jQuery selector string

What I want to accomplish I am looking to create an element that matches any given selector string. Here's a quick example: var targetString = "a.exaggerated#selector[data-myattr='data-here']"; var targetEl = $(targetString); if(!targetE ...

HTML5 Applications with Intel XDK

I'm currently working on an HTML5 application using Intel's XDK platform for building in Android. However, I'm facing an issue where the application crashes when the keyboard pops up upon entering text. Can anyone provide assistance with thi ...

Utilizing AngularJS to display an array of user inputs

Hey there, hope all is well with you! I have been working on an HTML form that looks like this: <div class="table-responsive " > <table class="table table-bordered"> <tr ng-repeat="x in [1, 2, 3, 4, 5]"> <td> <td align="center" ...

Change the structure of the content in a div

Seeking assistance with a slider code that switches between two dividers, previous and next. Each divider currently displays ten images in two parallel vertical lines. I am attempting to modify the layout so that each divider showcases five images on two p ...

How do I ensure that my font size completely fills the space in a justified layout using CSS?

Is there a way to style my text to match the appearance in the image shown using CSS? ...

What is the best way to contact all products that have been made by a specific User?

Using MongoDB with Mongoose, I have successfully implemented basic CRUD operations. However, I am facing difficulty in fetching all the products created by a specific user. I'm unsure if my approach is correct, but I attempted to use this syntax: user ...

Capturing the clicked element within a Vue (JS) instance by utilizing $(this) can be achieved by following these

I'm currently revamping an older application of mine and running into challenges with DOM manipulation and basic selections within a Vue instance. The data in my database is loaded via AJAX and each record consists of two parts: the header tab (title ...

Steps for embedding a webpage within a div element

I am facing an issue while trying to load a web page within a div using an ajax call. Unfortunately, it's not working as expected and displaying the following error message: jquery.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread ...

The data input from the HTML is not being correctly transferred to the modal

I am trying to transfer the reservation id from an HTML element to a modal window. When I click "cancel" next to a reservation, a modal should appear showing the reservation id. However, the modal pops up without displaying the reservation id. Can anyone h ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

A guide to troubleshoot and resolve the 500 (Internal Server Error) encountered during an Ajax post request in Laravel

I am facing an issue in my project where I am trying to store data into a database using ajax. However, when I submit the post request, I get an error (500 Internal Server Error). I have tried searching on Google multiple times but the issue remains unreso ...

Ways to ensure a div remains at the bottom of a page without using a wrapper

I am currently working on my website and this is the content I have in my body tag: #social-media { width: 175px; margin-left: auto; margin-right: auto; padding-top: 10%; } #social-media img { padding: 5px; } #soci ...

Should I use a single CSS file or separate CSS files for each page?

As I construct my website pages, I often ponder whether it's best to utilize separate stylesheets for each page or to have one comprehensive stylesheet for the entire site. In terms of loading efficiency, wouldn't having individual files be more ...

What is the best way to reference an Angular constant within a Gulp configuration file?

Is it possible to retrieve an Angular constant within a Gulp file? For example: angular.module('app').constant('env', { url: 'http://localhost:1337/' }); What is the method for accessing this constant inside a function ...

Press on a specific div to automatically close another div nearby

var app = angular.module('app', []); app.controller('RedCtrl', function($scope) { $scope.OpenRed = function() { $scope.userRed = !$scope.userRed; } $scope.HideRed = function() { $scope.userRed = false; } }); app.dire ...

Error: Attempting to access the 'createClient' property of an undefined object - TypeError

Recently, I've been working on a project where I needed to create and store a session in redis. To achieve this, I referred to the API documentation provided by this GitHub repository https://github.com/tj/connect-redis. However, I encountered an iss ...

In Internet Explorer 8, the PNG image is visible but in IE7, it myster

I have been trying to showcase a logo (PNG created in Paint.NET) on my website (XHTML 1.0 Transitional), using the following code: <body> <div class="header"> <div class="logo"> <img src="logo.png" /> </div> ...

Asynchronous update of array elements - lack of firing watch events

I have recently developed a component that showcases previews of blog articles. This particular component includes pagination functionality, where selecting a new page triggers the refreshment of the article previews array. The list of articles is obtained ...

Find out the dimension of an object's width

I have a container that I want to slide in and out of view on the screen when a button is clicked. The challenge is that I do not want to set a specific width for the container as it may vary in size. I attempted to achieve this with the following code, ...

Exploring the power of D3's nested appends and intricate data flow

Currently diving into the world of D3, I've encountered a perplexing issue that has yet to be resolved. Unsure if my confusion stems from a lack of familiarity with the library or if there's a key procedure eluding me, I feel compelled to seek gu ...