Absolute positioning causes an element's height to increase

As I delve into the realm of typographical animations and seek to calculate the baseline of a font at various sizes, I've stumbled upon a peculiar discovery: It appears that the height values of elements tend to increase in an erratic manner when their position is switched to absolute.

Heights without Position Absolute (tap to log heights)

const
  small = document.querySelector('#small'),
  large = document.querySelector('#large')

window.onclick = () => {
  console.log(small.getBoundingClientRect().height,
              large.getBoundingClientRect().height)
}
div {
  border: solid purple 2px;
}

#small {
  border: solid red 2px;
}

#large {
  border: solid black 2px;
  font-size: 10rem;
}
<div>
  <span id='small'>.</span>
  <span id='large'>.</span>
</div>

Heights with Position Absolute (tap to log heights)

const
  small = document.querySelector('#small'),
  large = document.querySelector('#large')

window.onclick = () => {
  console.log(small.getBoundingClientRect().height,
              large.getBoundingClientRect().height)
}
div {
  border: solid purple 2px;
}

#small {
  border: solid red 2px;
}

#large {
  border: solid black 2px;
  font-size: 10rem;
}

span {
  position: absolute;
}
<div>
  <span id='small'>.</span>
  <span id='large'>.</span>
</div>

Could someone shed light on this phenomenon?

Answer №1

Discover the secret lies within the display method, with no clear correlation to the height values due to differing calculations in each case.

For inline elements in the first scenario, expect the 'height' property not to apply as the content area's height is based on font properties such as the em-box or maximum ascender and descender. The vertical padding, border, and margin for an inline non-replaced box start at the top and bottom of the content area, unrelated to line-height calculations.ref

The span's height depends solely on font properties (font-family, font-size) along with the border top/bottom. Without delving into specific font details, it becomes challenging to pinpoint the exact calculation method.

Related:

Can specific text character change the line height?

What determines the space between the highest and lowest letter and the top and bottom border of the element the letter's in?


In the second instance, the span evolves into a block element through the use of position:absolute. Following the rule here: https://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-height, the height now equals the distance between the topmost and bottommost line boxes.

Thus, our element's height aligns with the line box defined by line-height, impacted by both line-height and vertical alignment but simplified when dealing with single characters.

Adjusting the default line-height set by the browser can yield desired height results:

const
  small = document.querySelector('#small'),
  large = document.querySelector('#large')

window.onclick = () => {
  console.log(small.getBoundingClientRect().height,
              large.getBoundingClientRect().height)
}
div {
  border: solid purple 2px;
}

#small {
  border: solid red 2px;
  line-height:1; /* will give a height = 1*16 + 4 */
}

#large {
  border: solid black 2px;
  font-size: 10rem;
  line-height:1; /* will give a height = 1*10*16 + 4 */
}

span {
  position: absolute;
}
<div>
  <span id='small'>.</span>
  <span id='large'>.</span>
</div>

Related: How does height will be calculated, based on font-size?


Converting the span element to inline-block produces parallel behavior to the second case following rules detailed here: https://www.w3.org/TR/CSS21/visudet.html#block-root-margin, leading to identical outcomes seen with absolute elements (https://www.w3.org/TR/CSS21/visudet.html#root-height). In this context, line-height dictates the element's height:

const
  small = document.querySelector('#small'),
  large = document.querySelector('#large')

window.onclick = () => {
  console.log(small.getBoundingClientRect().height,
              large.getBoundingClientRect().height)
}
div {
  border: solid purple 2px;
}

#small {
  border: solid red 2px;
  display:inline-block;
  line-height:1;
}

#large {
  border: solid black 2px;
  font-size: 10rem;
  display:inline-block;
  line-height:1;
}
<div>
  <span id='small'>.</span>
  <span id='large'>.</span>
</div>

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

The iOS website won't fully load until the button is tapped two times

- (IBAction)saveButton:(id)sender { NSURL *yourWebURL = [NSURL URLWithString: webpageURLLabel.text ]; NSURLRequest *webRequest = [[NSURLRequest alloc] initWithURL:yourWebURL]; if ([self checkIfValidURL] == YES) { [webpagePreview loadReq ...

Make a request to the local API in a React Native mobile app by sending a GET request

Currently, I am working on a mobile application using React Native and utilizing SQL Server and NodeJS. The API for this project is located in my localhost. Upon running the application on an emulator, I encountered an issue when attempting to make a reque ...

The behavior of -webkit-border-radius differs from that of -moz-border-radius

My website is displaying differently on Safari compared to Firefox. I want the CSS to make it look consistent across both browsers. I understand that I could use two div boxes - one for the outline and one for the image. However, I prefer how Firefox only ...

The concept of immutability is crucial when utilizing a for-in loop to append an object to an array

Within my code, I have a nested loop structure consisting of a for of with a for in loop inside it. This setup retrieves information from a Neo4J database. By utilizing the Object.assign method, I am able to transfer a property from the fetched object into ...

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...

When utilizing the Express framework, the object req.body is initially empty when collecting data from a basic

I'm encountering an issue where I receive an empty object in req.body when submitting my HTML form. This problem persists whether testing in Postman or directly submitting the form from localhost in the browser. Upon logging it in the node console, t ...

What is the best choice for code design patterns in a nodejs environment? What are the key considerations for creating a well-

Although I have a background in games development using C/C++/C#, I have recently delved into automated testing and now I am eager to learn more about backend development. My current project involves creating a platform for automated backups, building fr ...

Is it possible to simultaneously center and display an iframe inline?

I have a YouTube video that I'm trying to center within a div. After adding display: block; to the CSS following advice from How to center an iframe horizontally?, it centers correctly, but now I want to display two images inline next to the iframe ...

Issue with Angular's ngOnChanges Lifecycle Hook Preventing Function ExecutionWhen attempting to run a function within Angular's ngOn

In the midst of my evaluation process to ensure that specific values are properly transmitted from one component to another using Angular's custom Output() and EventEmitter(), I am encountering some issues. These values are being sent from the view of ...

scrollable material ui chips list with navigation arrows

I'm attempting to create a unique scrollable chips array using Material UI version 4 (not version 5). Previous examples demonstrate similar functionality: View Demo Code I would like to update the scrolling bar of this component to include l ...

What could be the reason why certain animations fail to run on specific icons when hovering over the parent element?

I recently launched my website which features a series of tabs with unique icons. Some of the icons, labeled as soap-icon, have animated effects while others, categorized under icomoon-icon, do not. Upon checking the console, I discovered that the animati ...

Ways to show or conceal content using only CSS

Looking for help with switching content using pure CSS. I'm not very skilled with CSS and would prefer to avoid using JavaScript if possible. Any assistance would be greatly appreciated. Below is a snippet of the code: If A is clicked, toggle-on-con ...

Reading Properties in VueJS with Firebase

<template> <div id="app"> <h1 id="title"gt;{{ quiz.title }}</h1> <div id="ques" v-for="(question, index) in quiz.questions" :key="question.text"> <div v-show="index = ...

Utilizing database information to dynamically select Nightwatch.js tests for execution

Currently, I am in the process of configuring nightwatch tests for a specific website. The setup involves assigning testing personas to run tests, which works smoothly in our development environment. However, we face an issue when we need to dynamically ad ...

Place a <ul> list in the center

I've hit a roadblock trying to find a solution for this issue. Nothing I've attempted so far has proven successful. I'm hopeful that someone could lend me a hand. The challenge at hand involves centering a standard <ul> list on the pa ...

Encountering a 500 internal server error while trying to submit a form via AJAX and

I'm a beginner in PHP and I'm facing issues with sending test emails from my local host. My form consists of 3 fields, and I want the user to be able to submit the form and see a success message without the page refreshing. Although I have set u ...

When an image is clicked, I am attempting to access data from a Sharepoint list

In my Sharepoint list, there are three columns: Image, Title, and Description. I am using ajax to retrieve the items from the list. The images can be successfully retrieved, but my goal is to display the title and description of the clicked image when an ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...

My child template in Angular UI is not loading properly due to the presence of multiple views when the URL changes

After reviewing a couple of questions similar to this on various forums, I may have overlooked a crucial detail in them. Upon loading http://localhost:8000/characters/#/mages/detail/3, I am being redirected to my 'otherwise' URL: $urlRouterProvi ...

The task "default" is not found within your current gulpfile configuration

After running gulp in my console, I encountered the following error: Task 'default' is not in your gulpfile I double-checked my gulpfile and it appears to be correct: var gulp = require('gulp'), LiveServer = require('gulp- ...