skip to Main Content

I have created a simple popup div (for offering auto-complete options), which I want positioned at the point in the text where it was created, but overlaying rather than displacing other content. So in CSS I have set, for this div:

position: absolute;
z-index: 1;

This works exactly as I want except that the popup does not move when the other content that it overlays is scrolled. The definition for absolute position (on W3Schools) says:

An element with position: absolute; is positioned relative to the
nearest positioned ancestor (instead of positioned relative to the
viewport, like fixed) … However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

None of the other elements on my page have an position explicitly specified i.e. they all use the default (static) position. So the second half of the above description sounds to me like absolute is the right option for what I want. The only other position options that work with z-index are: relative, fixed, sticky – and none of them fixes the issue anyway.

What am I missing?

2

Answers


  1. Chosen as BEST ANSWER

    I eventually found the answer by trial-and-error. To make position: absolute work as described, I had to define one of its ancestors to have an explicit position (I used relative). (This still seems at odds with the description for position that I quoted above).


  2. body {
        font-family: Arial, sans-serif;
    }
    
    .content-container {
        position: relative;
        padding: 20px;
        border: 1px solid #ccc;
        height: 400px; 
        overflow-y: auto; /* enables scrolling within this container */
    }
    
    .popup {
        position: absolute;
        z-index: 1;
        top: 100px; 
        left: 100px; 
        background: #f9f9f9;
        border: 1px solid #ccc;
        padding: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Popup Example</title>
    </head>
    <body>
        <div class="content-container">
            <p>Your content goes here. Scroll to see the popup move with the content.</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <div class="popup">Autocomplete options</div>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
            <p>More content...</p>
        </div>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search