Why does a relatively positioned element always begin at the top corner of the window?

I am really struggling to understand the concept of relative versus absolute positioning, especially when dealing with parent or grandparent elements that have position values. Can someone please help me clarify these two scenarios:

Case 1:

  • grandparent - absolute
  • parent - relative
  • child - absolute

Case 2:

  • grandparent - absolute
  • parent - relative
  • child - absolute

However, in this case, the parent is not directly nested within the grandparent like shown below:

<div class="grand-parent">

</div>

<div class="parent">
     <div class="child">

     </div> 
 </div>

Here is a link to a fiddle where I've been working on this issue: https://jsfiddle.net/4KUWc/32/

My questions are:

  • I'm having trouble seeing the difference between the two cases mentioned above. Shouldn't case 2 have the parent div start after the grandparent? Why does it seem to take (0,0) coordinates?
  • If a relative element has an absolute parent, will it follow the positioning of the absolute parent or will it maintain its independence?
  • Is it possible to have relative children with an absolute parent?

Answer №1

position:absolute

When using position:absolute, the relational positioning attributes (such as top, bottom, right, etc.) are calculated from the closest ancestor that has a position value other than static. If no such ancestor exists, the <body> element will be used as reference.

position:fixed

With position:fixed, the relational positioning attributes are calculated based on the closest viewport, which is typically the <body> element. However, if an element is 3D transformed, it can act as its own viewport for its children - more details can be found in Eric Meyer's article on Unfixing fixed elements with transforms.

Both absolute and fixed positions remove the element and its children from the content flow of their parent, making them essentially invisible to subsequent elements in the DOM.

position:relative

Elements with position:relative have their relational positioning attributes calculated based on where they would normally appear in the parent's content flow, even after applying relational positioning attributes. Unlike fixed and absolute positions, relative position does not remove the element from the parent's content flow.

Answer №2

It's important to remember that there is no magic trick involved in understanding how each position works. Here is a brief summary to help clarify:

  • All elements are initially set to position: static, causing them to stack on top of each other, or inside one another if nested.
  • If an element has display: none or its width and height set to 0px, it will not take up any space and other elements will render as if the hidden element didn't exist.
  • The CSS properties top, bottom, right, left, and z-index have no effect on elements with a static position. For these properties to work correctly, the element must be positioned as relative, absolute, or fixed.
  • relative and static positions are similar, but relative takes into account properties like top, bottom, right, left, and z-index.
  • An element with a relative position is placed relative to its parent position.
  • Elements with absolute or fixed positions are similar, except absolute elements are positioned relative to the body, while fixed elements are positioned relative to the window (referencing @AndreiGheorghiu's explanation about fixed position and 3D transform).
  • An absolute element is positioned relative to its nearest non-static parent. If all parents are static, then the element will be positioned relative to the body.

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 Material-UI Menus

I need the menu to adjust its height dynamically as the content of the page increases vertically. Even though I have applied "height:100%" in the styles, it doesn't seem to work. Can anyone assist with this issue? Here is the code snippet: import R ...

Modifying the page header content using JavaScript

There's this snippet of code that alters the image on another page: <div class="imgbx"> <button onclick="window.location.href='index.html?image=images/xr-black.jpg&tit=XR-black'" >Invisible ...

Customizing the appearance of the file input type using an image in HTML and CSS

Can you provide guidance on utilizing the image below? Is there an alternative approach to using: <input type="file" /> ...

Creating a clickable link that dynamically updates based on the span and id values, and opens in a new browser tab

I am attempting to create a clickable URL that opens in a new window. The URL is being displayed and updated on my HTML page in the following manner: Python Code: def data_cb(): return jsonify(waiting=await_take_pic()) Javascript Code: jQuery(d ...

Adjusting diagram size based on screen width using Bootstrap and jQuery

I recently created a diagram that adjusts its size according to the screen width. However, when I implemented this code on my page, I encountered an issue where the final circle or glyph would drop to the next line instead of staying on the same line as in ...

Is there a way to preserve the original color format without converting it to RGB

When applying a hsl color in JavaScript, it ends up being converted to RGB instead of staying as an HSL color. document.body.style.backgroundColor = "hsl(0,100%,50%)" document.body.style.backgroundColor; // "rgb(255, 0, 0)" I wanted to set an HSL color a ...

What could be the reason for the body background color refusing to change

I'm currently working on a JavaScript calculator project and I'm using this code snippet from codepen. The issue I'm facing is that despite setting the body background color to black, it still appears white. Could there be a spacing problem ...

PHP Table Sorting Functionality

After inputting the correct code, I am still facing an issue with the table sorting not showing up. Can someone assist me with this problem? I have included both my CSS styles and PHP coding. Thank you for your help! Here is a visual representation of the ...

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Issues with CSS rendering have been encountered on the Facebook page

I'm experiencing an issue with the rollover CSS on Facebook's rendering engine. I'm not sure if I made a mistake in my code or if there are limitations with certain CSS properties on custom Facebook pages. Here is the code I am using: <l ...

Interested in mastering BootStrap for Angularjs?

As a PHP developer with a newfound interest in JavaScript, I took it upon myself to learn AngularJS and jQuery. However, I recently discovered that simply mastering Angular is not enough - Bootstrap is also necessary. My only issue is my fear of CSS; handl ...

Position two div elements so that the second div expands to occupy the entire available space

I am struggling with aligning two divs within a container div, one on the left and one on the right. I am using flexbox for alignment purposes, as shown in the code snippet below. .box { display: flex; align-items: center; just ...

How to use jQuery to select an element by using 'this' on a button

I have a total of 5 divs, each containing 5 different texts. <div class="text"> <%= theComment.text %> </div> I am working with node.js, MongoDB, and Mongoose. In addition to the divs, I also have a button labeled EDIT with a cl ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Searching for a JavaScript tool that offers syntax highlighting capabilities

I have come across some excellent RTE HTML text editors such as jsredaktor, TinyMCE, and FCK Editor, but I am in search of an HTML/JavaScript component that functions similarly to a TEXTAREA with built-in code syntax highlighting. ...

HTML dynamic voting system

I'm new to coding in HTML and I have a specific challenge that I need help with. I want to display a value on my webpage that increases every time a user clicks a button. Below is the code I have written so far: <script type="text/javascript& ...

Why is the Bootstrap template working on index.html but not on any other React components?

Greetings to all who stumble upon this post! Hello, I have been diligently working on a React application and am eager to integrate a Bootstrap template. However, everything seems to be in order except for the responsiveness of the template. It lacks anim ...

Design and styling with HTML5 and CSS

Having a small issue with my code as I venture back into coding after a long hiatus, resulting in me forgetting some basics. Currently, I am attempting to create a simple HTML layout. Upon inspecting the page, I noticed that it appears slightly longer tha ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...