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

Overlapping Dropdown Javascript Menus

To achieve the desired effect in the header, I need to create two expandable dropdown menus for the first two titles. My coding experience is limited, especially when it comes to javascript and jquery. Currently, I have managed to create the effect for one ...

Creating a lively JQ plot and saving it within an HTML file from a .aspx page using C# .net

I am currently in the process of developing a web-based application using Bootstrap. My goal is to save a .aspx page as an HTML file within my application. Upon writing the code: using System; using System.Collections.Generic; using System.Linq; using S ...

Using JQuery to animate a division towards the left

Currently, I am in the process of developing a website that is meant to incorporate JQuery Animations. My goal is to create an animation effect for the menu items so that each item moves to the right when the mouse hovers over it. Despite my efforts to fi ...

Styling emails in an inbox with CSS

I am developing an email application and aiming for the inbox layout to be similar to that of Mac Mail. The emails are fetched from a database using ajax, outputting to XML. I then loop through the entries to extract the necessary elements. My concern li ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

Locate specific elements on a webpage without scanning through the entire content

Is there a way to optimize the performance of getElementsByTagName("td") so it doesn't search the entire document? I'm experiencing long wait times for results. Here is an excerpt from my code: $ie.Document.getElementsByTagName("td") | ? {($_.c ...

"Resolving the issue with unnecessary line breaks in Optimizepress when input is contained within a paragraph

I am experiencing an issue with the code on my server: <p>This is a test to determine why the <input type="text" style="text-align: center;" value="input"/> element appears on a new line when displayed on a wordpress page.</p> When view ...

Is there a way to adjust the transparency of a span element's background without affecting the text itself?

I have some code that needs to be customized. This is my HTML: <div class="text-rotator add-top-half add-bottom-half align-left white-txt medium-txt uppercase highlight-bg"> <div class="rotator-wrap" style="display: block;"> <sp ...

using hover/click functionality with a group of DIV elements

I have a group of DIV elements that I want to apply an effect to when hovering over them with the mouse. Additionally, when one of the DIVs is clicked, it should maintain the hover effect until another DIV is clicked. <div class="items" id="item1"> ...

How can the default text color be adjusted in NSAttributedString when initialized with HTML dark mode?

During the process of converting my existing app to dark mode, I came across an instance where I needed to initialize a UITextView with an NSAttributedString for displaying some legal text from the app store. While everything looked good in light mode, swi ...

Expansive dropdown options in the navigation bar

Can someone help me create a menu similar to the one in this screenshot? I am looking for a solution where hovering over a cursor will open a large submenu with two sections. Any examples or suggestions would be greatly appreciated. Thank you all in advan ...

Is there a way for me to view the contents within the box?

Hey there! I have a question about how to access the content inside this mysterious box "" within the style sheet. For instance, I am curious to find out the link of the image: .facebookicon::before { content: ""; } ...

Tips for inserting a rotated image using CSS

I've created the following code snippet. However, there is a new requirement stating that the image needs to be rotated by 180 degrees. How can I make this happen? #cell { background-image: url("../images/logo.PNG"); background-attachment: fixed; b ...

The HTML form is not displaying any content and instead is returning "Not a Number

I've been struggling to create a form that can generate a numerical value based on the input from two fields. Specifically, I need to calculate the output by subtracting the product of two values - one entered in an input field and another selected vi ...

Styling rounded buttons with GTK and CSS

In my C++ application, I am attempting to create a rounded button by utilizing an external CSS file. Although I have successfully achieved a round button, there is still a pesky rectangular border that remains and I am struggling to figure out how to remo ...

Conceal button divider on pager in Jqgrid

Within my grid setup, there are 3 buttons placed in the pager section: 'Refresh', 'Constution', and 'Developed'. These buttons are separated by two vertical navSeparators. Upon grid load, the 'Developed' button is hi ...

Using JavaScript to dynamically load Cascading Style Sheets based on the current

I am trying to dynamically load different CSS files based on the current date (season). I attempted to tweak an image script that I found on Stack Overflow, but it didn't yield the desired result. Could someone please guide me on where I might be ma ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Modifying the default text within a select box using jQuery

Within a select box identified as 'edit-field-service-line-tid', there is default text displayed as '-Any-'. This particular select field has been generated by Drupal. I am looking to use jQuery to change the text '-Any-' to ...