When utilizing position:absolute, the closest ancestor with a defined position is not influencing the element

In my HTML code, I have a parent div that contains an image, and a child div that holds another image. I wanted the child image to appear in the top-left corner of the parent image by setting the position of the child image to absolute, and the parent's position to either relative or absolute.

According to W3Schools, for the absolute property to work correctly, the element should be positioned relative to its first non-static ancestor element. So, I assumed that I needed to set a non-static position for the parent.

However, I was surprised to see that even without setting the position of the parent (defaulting to "static"), the child image still appeared nicely in the top-left corner.

I am now wondering why I did not have to set the position of the parent to a non-static value for the absolute property to function properly. Did I misunderstand how absolute positioning works?

<div class="parent">
    <img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300">
  <div class="child">
    <img src="http://xiostorage.com/wp-content/uploads/2015/10/test.png" width="200">
  </div>
</div>

/*.parent {
  position:relative;
}*/

.child {
  display:none;
  position:absolute;
  left:0;
}
.parent:hover .child {
  display:initial;
}

View the JSFiddle example here.

Update: Connexo provided an updated code snippet.

Try uncommenting the position for the parent to uncover the mystery. For more information, refer to the accepted answer below.

<h1>
   Positioning test
</h1>
<div class="parent">
    <img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300">
  <div class="child">
    <img src="http://xiostorage.com/wp-content/uploads/2015/10/test.png" width="200">
  </div>

/*
.parent {
  position:relative;
}*/

.child {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
}
.parent:hover .child {
  display:initial;
}

Answer №1

Remember these two key guidelines:

  • An absolutely placed element will be placed within its containing block, which is determined by the nearest positioned ancestor. However, if there is no positioned ancestor, the containing block becomes the initial containing block (i.e., the viewport).

    Your .parent div is currently aligned at the top-left corner of the viewport. This explains why your absolutely placed child will have a similar position in either containing block.

  • When you set position: absolute on an element, it is taken out of the normal flow of the document. The element will still be positioned as if it were part of the normal flow until you use CSS offset properties (left, right, top, bottom) to actually position it.

Answer №2

It seems like you missed out on setting the top property in your JSFiddle, causing everything to align to the left side of the page where the image was located. Once you include top: 0px in your JSFiddle, you will see that the image will be positioned in the top left corner of the page.

Check out the simple demo below with the addition of the top property and a margin pushing the .parent element away from the corner.

.parent {
  margin: 30px;
  /* position: relative;*/
}
.child {
  display:none;
  position:absolute;
  left:0;
  top:0;
}
.parent:hover .child {
  display:initial;
}
<div class="parent">
    <img src="https://lh4.ggpht.com/wKrDLLmmxjfRG2-E-k5L5BUuHWpCOe4lWRF7oVs1Gzdn5e5yvr8fj-ORTlBF43U47yI=w300">
  <div class="child">
    <img src="http://xiostorage.com/wp-content/uploads/2015/10/test.png" width="200">
  </div>
</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

How can grid be used in CSS/HTML to create two collapsible columns that are side-by-side, maintain equal width, and keep their size when expanded?

Hello all, I'm new here and I have a question that I hope I can explain clearly. I am currently working on creating two collapsible "buttons" positioned side by side (each taking up half of the screen width), which expand when clicked to reveal an equ ...

adding content to div is becoming less speedy

Currently, I'm developing a drawing board using only html/css/jquery and the drawing functionality is working smoothly. The approach I've taken involves capturing the mousemove events and placing a dot (div) at each point where the event occurs, ...

Is the ID selector the quickest method in jQuery and CSS?

Which is the optimal choice in jQuery/javascript for speed? $('#myID .myClass') or $('.myClass') What is the preferred option to utilize in CSS? #myID .myClass{} or .myClass{} In hindsight, I realize my explanation was insuffici ...

The rating and comment section is failing to adapt to smaller screens, creating a terrible user experience

I am a beginner with Sass and CSS. I wanted to create a rating and comment section which looks fine on a laptop screen, but appears off on smaller screens. It seems like the layout might be incorrect or maybe I didn't follow grid layout guidelines pro ...

"Perfectly Centered: Aligning Vertically and Hor

My goal is to center a box vertically and horizontally, but I'm struggling to get it just right: HTML: <div id="wrapper"> <header> <div id="logoWrapper"> <div class="logo">Logo Here </di ...

Tips for concealing all items except the currently selected branch when clicking on a menu drop-down

I am seeking a solution to open only one node at a time on click, and remove the 'is-active' class from other items. Currently, there is excessive space taken up after opening multiple menu items. I want to ensure that only one node is open at a ...

Exploring the world of animation with Jquery and images

I'm delving into the world of jQuery to create some captivating animations. Currently, I've been tasked with an assignment involving images that expand, contract, change opacity, and eventually hide. Below is my code snippet: function play_pic1 ...

Steps for revealing all the information from a database when clicking on the 'Read More' button

I recently set up a database called Magazine, featuring a table named social_media. This table consists of 5 columns: ID, Headline, Author, Content Short, Content. The Content Short column contains condensed versions of the articles which are displayed on ...

The hover action in the Jquery Accordion does not activate when a section has been opened before

I'm facing a problem with my jQuery accordion menu. After opening and closing a section, the ':hover' effect stops working only for that specific section. However, it continues to work for other sections that haven't been clicked yet. ...

Is it possible to utilize the same module.css file across multiple components in a React project?

As a newcomer to React, I have discovered the benefits of using module CSS to address naming conflicts. Now, as I prepare to refactor my app, I have encountered a scenario where two components are utilizing styles from the same file. I am curious to lear ...

What could be the reason for the presence of three pixels of white space below this particular table

My table is supposed to have a fixed height of 146px, but there seems to be an extra row of three pixels at the bottom. I've tried various methods to remove any unwanted spacing or padding, but nothing has worked so far. The only solution I found was ...

Tips on resizing an image right before saving it to a folder in order to ensure it has a consistent height within a Bootstrap 4 card while using Flask

I am working with Bootstrap 4 cards and facing an issue with variable-sized images when using card-img-top to make them responsive. The images are inputted using AJAX to the backend, and I need to reduce their size (height and width) for better responsiven ...

The footer refuses to stay positioned at the bottom of the page

Can you help me locate the CSS style for the footer? #footer { background-color: #000; bottom: 0px; color: #fff; clear: both; text-align: center; padding: 5px; } What is the best way to ensure the footer is positioned at the bottom of ...

Aligning CSS Divs with Changing Content

Can someone help me with a CSS and DIV tags issue? I have a dynamic webpage and need guidance on creating a container DIV. Depending on the scenario, this container DIV will either hold one DIV with 50% width that needs to be centered or two side-by-side D ...

Customizing CSS according to specific URLs

I have two different domains - one ending with .nl and the other ending with .be. For instance, domain.nl and domain.be. Both domains share a similar overall style, but I want certain elements to have distinct styling depending on whether it is the .nl o ...

What is the best way to apply a png overlay to each img tag when hovered over?

Here is the code snippet I am working with: <div class="latest-post"> <a href="http://localhost/blaze/2011/documentaries/test-big-thumb" rel="bookmark"> <span> <img width="140" height="100" src="http:// ...

Issue with the hamburger menu dropdown color not being applied properly

Greetings to all who are taking the time to review this query! Everything seemed to be going well until I refreshed my code after making numerous changes, and then this issue arose: Dropdown menu lacking color: https://i.sstatic.net/3lz5a.png The color ...

Designing div arrangements

I am trying to create a layout of divs similar to the one shown in the image: https://i.sstatic.net/DLUe8.png The challenge I am facing is that I need to arrange them in a row, with one large div in the center and four smaller divs on the sides. I am plann ...

"Revolutionizing the way we navigate: Angular's innovative

Presently, my focus is on incorporating route transitions into my project. I've employed a component that appears on click and triggers the corresponding service function: routeTransition(destination) { if (this.router.url !== destination) { t ...

Ways to set control values with AngularJS

After retrieving a single record from the database for my detail view, I need to assign data to controls. Take a look at my code snippet below: var app = angular.module("MyProductApp", []); app.controller("ProductsController", function ($scope, ...