Guide on aligning text along a baseline

CLICK HERE TO ENTER THE INTERACTIVE PLAYGROUND

HTML:

<div class="first">Text A</div>
<div class="second">Text B</div>

CSS:

div {
  background-color: rgba(255, 0, 0, 0.3); /* For visualization only */
  margin-top: 50px;                       /* For visualization only */
  height: 20px;                           /* This is fixed! */
}

.first {
  font-size: 16px;                        /* This can change */
}

.second {
  font-size: 30px;                        /* This can change */
}

Result:

How can you align the baseline of text with the bottom of the pink box?

Is there a way to achieve this layout regardless of the font size?

CLICK HERE TO TRY IT OUT

Answer №1

After extensive searching, I stumbled upon an incredible tutorial from Adobe that explains how to align text to the baseline of an element.

USING PSEUDO-ELEMENT

I highly recommend this method, but let's delve into the details below (Journey from .strut element to a single pseudo-element):

div {
  width: 400px;
  height: 100px;
}
.first {
  font-size: 24px;
  background-color: #9BBCE3;
}
.first::after {
  content: "";
  height: 100%;
  display: inline-block;
}
<div>
  <div class="first">Hello g World / With font-size: 24px</div>
</div>

USING AN EXTRA .STRUT ELEMENT

  • SCENARIOS AND RULES

Rule 1 (Larger Fonts): The height of the div must be fixed, e.g., 20px. Therefore, the font-size should be equal to or less than the .height value to work properly.

~ THE FONT-SIZE SHOULD BE EQUAL TO OR LESS THAN THE FIXED HEIGHT FOR IT TO WORK WITH SMALLER VALUES AS WELL

Scenario 1: Assume we have larger fonts than the 20px specified in this case.

View it live: http://jsfiddle.net/csdtesting/pvw5xhku/

div.forall {
  width: 700px;
  height: 48px;
  border: thin black solid;
  background-color: #9BBCE3;
  margin-top: 20px;
}
.inText {
  font-size: 48px;
  line-height: 48px;
}
.inText3 {
  font-size: 22px;
  line-height: 22px;
}
.strut {
  height: 48px;
  display: inline-block;
}
<div class="forall">
  <div class="inText">Hello g World /With font-size 46px
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div class="inText2">Hello g World /With font-size 32px
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div class="inText3">Hello g World /With font-size 32px
    <div class="strut"></div>
  </div>
</div>

  • EXPLANATION

The secret behind this technique lies in the .strut element, specifically its property display:inline-block;! It's truly fascinating how it works!

The baseline of the strut aligns with its bottom margin edge, influenced solely by the strut's height. If the line height of the text is smaller than the strut's height, the baseline of the text adjusts accordingly. Mind-blowing!

  • MAIN IMPLEMENTATION

See it in action: http://jsfiddle.net/csdtesting/bm2yz3ec/

div.forall {
  width: 300px;
  height: 20px;
  border: thin black solid;
  background-color: #9BBCE3;
  margin: 10px;
}
.inText {
  font-size: 20px;
  line-height: 20px;
}
.intext2 {
  font-size: 9px;
  line-height: 9px;
}
.strut {
  height: 20px;
  display: inline-block;
}
<div class="forall">
  <div class="inText">Hello g World /With font-size 20px
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div>Hello g World / Without font-size
    <div class="strut"></div>
  </div>
</div>
<div class="forall">
  <div class="intext2">Hello g World / with font-size:9px
    <div class="strut"></div>
  </div>
</div>

Answer №2

Yes, it is possible to adjust the positioning of text to some extent using a combination of CSS properties. This includes manipulating the line height, setting margins and padding, or using positioning properties like `position: relative` and `top`. Different techniques can be used depending on whether you are working with one line of text or multiple lines.

However, it's important to note that the rendering of text can vary across different operating systems and browsers, making it challenging to achieve precise control over the positioning of text.

Browsers typically position text in the middle of the line by default, based on the defined line height. There is no universal baseline for text across browsers, so the positioning of text may differ between browsers.

Creating a vertical rhythm involves ensuring that all text aligns at specific intervals. This requires controlling the font size, line height, and other elements that contribute to vertical spacing in your design. By selecting a "rhythm unit" and setting your text to align with it, you can maintain consistency in your design. The combination of borders, padding, and margins should add up to your rhythm unit to keep everything in line.

To illustrate these concepts, I have created a JS Fiddle example with code snippets.

When it comes to vertically centering text, the browser handles this automatically, which can result in text not aligning perfectly with a grid. To address this, there are different approaches you can take.

Here is a sample HTML structure:

<article>
  <section>
    <h2>Title!</h2>
    <div class="first">Hello g World<br />Lorem ipsum...</div>
    <div class="second">Hello g World<br />Lorem ipsum...</div>
    <div class="first">Hello g World<br />Lorem ipsum...</div>
  </section>
</article>

By applying basic CSS styles to the elements, such as setting line heights and font sizes, you can control the vertical alignment of text within your design.

Techniques for Positioning Text:

You can use `position: relative` and `top` to visually align text by positioning it relative to a grid in the background.

Here's an example of how this can be implemented in CSS:

.rel, .rel .first, .rel .second {
   position: relative;
}
.rel .first {
    top: 4px;
}
.rel .second {
    top: 9px;
}

Another method involves using padding and margin to adjust the vertical position of text, ensuring that the sum of top and bottom padding equals the rhythm unit.

For more details and additional methods for establishing vertical rhythm, I recommend reading articles on this topic such as the ones found on 24ways and A List Apart. Vertical rhythm generators can also be useful tools to maintain consistency in your design.

Answer №3

Ensure to include the line-height attribute:

div {
  background-color: rgba(255, 0, 0, 0.3); /* Visualization only */
  margin-top: 50px;                       /* Visualization only */
  height: 20px;                           /* Fixed height */
  line-height: 20px;
}

UPDATE

Align text vertically by centering with matching values for height and line-height:

JSBIN

If using only 16px and 30px works for you, great. For universal compatibility, consider an alternative layout such as the following:

<div class="container">
  <span class="align-bottom">Hello g world</span>
</div>

Answer №4

There doesn't appear to be a CSS property specifically for this situation, and it seems unlikely that you can determine it programmatically.

Nevertheless, you have the option to modify the height of the div using JavaScript, considering that the portion of the font above the baseline is about 80%:

var divs = document.getElementsByTagName('div');
for(var j = 0 ; j < divs.length ; j++) {
  divs[j].style.height= divs[j].offsetHeight*0.8+'px';
}

Make sure to remove the fixed div style height beforehand.

Check out the Fiddle here: http://jsfiddle.net/38eLft8q/1/

Answer №5

It may be a bit challenging and not completely foolproof, but here's what's been done so far:

HTML

<div class="first"  title="Hello g World"></div>
<div class="second" title="Hello g World"></div>

CSS

div {
  background-color: rgba(255, 0, 0, 0.3);
  margin-top: 50px;
  height: 20px; /* This size is fixed! */
  position: relative;
}

div:before {
   content: attr(title);
   position: absolute;
   bottom: -0.24em;
}

.first {
  font-size: 10px;
}

.second {
  font-size: 16px;
}

JSBIN

appreciate the challenge :)

UPDATES:

If we want to keep the structure of the question unchanged, we can maintain the text within the divs:

<div class="first">Hello g World</div>
<div class="second">Hello g World</div>

and use some JavaScript to generate the titles

var divs = document.getElementsByTagName("div"); 

for (var i = 0; i < divs.length; i++) {  

    var txt = divs[i].innerHTML;
    divs[i].setAttribute('title', txt);

}

then make some CSS adjustments

div {
  background-color: rgba(255, 0, 0, 0.3);
  margin-top: 50px;
  height: 20px; /* This size is fixed! */
  text-indent: -9999px;
  position: relative;
}

div:before {
   content: attr(title);
   text-indent: 9999px;
   position: absolute;
   bottom: -0.24em;
}

JSBIN

If we're open to changing the structure, it can be like this:

HTML

  <div class="first"><span>Hello g World</span></div>
  <div class="second"><span>Hello g World</span></div>

CSS

div {
  background-color: rgba(255, 0, 0, 0.3);
  margin-top: 50px;
  height: 20px; /* This size is fixed! */
  position: relative;
}

div span {
   position: absolute;
   bottom: -0.24em;
}

JSBIN

NOTE:

  • Not tested with different fonts, but I believe it should work as long as you adjust the bottom position accordingly.

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

Troubleshooting a problem with scrolling functionality while keeping the header in place and ensuring the correct tab is highlighted

I've successfully created a page with a fixed menu that appears when scrolling, and the tabs activate based on their corresponding section IDs. However, I'm encountering some issues: The scrolling behavior is not precise; when scrolling to sec ...

Strange occurrences observed with the interaction of multiple CSS classes

Recently, I encountered a situation with a class that had me puzzled. .lifetime .containerrow { text-align: center; height: 20px; } To enhance the appearance of certain elements by making their text bold, I attempted the following: .lifetime .co ...

Switch between the table data elements in an .hta document

The response provided by Dr.Molle in a previous post here was accurate, but it only functioned with <div>. I am required to utilize <table>. Though I found a script that works flawlessly outside of my VBScript, it does not work when embedded in ...

How to ensure onmouseenter and onmouseleave work properly in Chrome using HTML, JavaScript, and jQuery

<div style="position: relative; left: 50px; top: 30px; width: 300px; height: 150px; background: #222222;" onmouseenter="this.style.background='#aaaaaa'" onmouseleave="this.style.background='#222222';"></div> http://jsfiddle ...

Utilizing jQuery Methods within Node.js

Recently delved into the world of node.js and created multiple pages (such as login, signup, blog, etc). If I desire an effect in which: 1. Hovering over the "News" button triggers a slider to appear downwards, To make adjustments to an image within ...

The content is not adapting properly for mobile devices (Bootstrap)

Currently, I am in the midst of a project and require assistance in ensuring an element on my webpage is responsive. Specifically, I need the text within a box to overlap the accompanying image when the browser window is resized. Should I add a class to th ...

hover causing the table cell to act erratically

My table consists of three cells with widths of 30%, 40%, and 30% respectively. The table itself occupies 25% of its container, which can range from 1024px to 400px. The first cell contains a button labeled GALLERY. Upon hovering over the cell, the text c ...

Finding the chosen selection in AngularJs

I've been working on this script for hours and I'm struggling to output the text instead of the value of a select option in AngularJS in HTML through data binding. Despite my efforts, I keep getting the value instead of the text. How can I resolv ...

Setting expiration dates for cached images

I am interested in optimizing the loading speed of my webpage by setting an expiration date for images. However, I am unsure about where to specify this. The images on my website are loaded via CSS from Cloudfront using an S3 bucket in AWS. Can you provid ...

Python Selenium cannot locate button within an iframe

click here for imageI am trying to interact with the "바카라 멀티플레이" button located at the center of the website. Even after switching into an iframe, I am unable to detect the button. How can I achieve this? from selenium import webdriver im ...

Control input for filtering and searching using Bootstrap

My goal is to create a search and filter user input field. I found an example on an old bootstrap page that showcases exactly what I need, but I'm facing some issues with displaying the results. Here's the Bootstrap example page. The search bar ...

Struggling with proper vertical alignment using Flexbox and achieving center alignment

I've been using JavaScript for displaying dynamic text and images, but I'm facing some formatting issues. Currently, I'm utilizing display: flex to position the text and image next to each other, but I'm struggling with horizontal alig ...

Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly fil ...

Customize your radio buttons to display as stylish boxes with Bootstrap

Check out my Fiddle here... The radio buttons are displaying correctly in the fiddle. <div class="element-radio" title="Do you want to float the text to the left, right, or not at all?"><h4 class="title" style="font-weight: bold;">Float (left ...

Edit the alternative text for an image tag to suit your needs

Is there a way to move the displayed mini popup to the left of the mouse cursor when a user hovers over an image with the following code: <img src="image" alt="product code 000000"> I noticed that the default alt text always appears on the right of ...

What is the best method for efficiently loading SVG icons on an HTML page without redundancy? / Is utilizing <use href> recommended?

My struggle with implementing icons in Angular While working on a new Angular project, I've encountered challenges with my current SVG-icon implementation method from a previous project (@ngneat/svg-icon). The process involves organizing SVG files in ...

The see-through background causes my text to blend in seamlessly as well

While creating a text box with a black transparent background, I encountered an issue where the text also became transparent. Can someone please point out where I went wrong? style.css #headertxt { position: absolute; right: 20px; bottom: 100px; backgr ...

Optimize data storage with javascript on Otree

I've been attempting to store the timestamp from a click in an Otree database, but I've tried using various codes without success. Here's the first code snippet: function myFunction() { var n = Date.now(); document.getElementById(" ...

Is it possible to dynamically load a specific div when the page loads, relying on the

I am using JQuery SlideUp and slideDown methods to toggle the visibility of panels. How can I load or display the first record's contact information as a default? Currently, it loads blank because I set the panel's display property to none: < ...

What is the best way to say hello using jQuery?

I need some assistance with a task that involves entering my name into an input field, clicking a button, and having an h1 tag display below the input saying Hello (my name)! Unfortunately, I am struggling to figure out how to achieve this. Below is the H ...