简体   繁体   中英

How do I absolutely position a relatively positioned element?

Let's say I have a container, and that I want to put this one container into yet another container that's also full of other stuff. The CSS code might look something like this:

.parent-container {
    width: 100%;
    position: relative;
}
.child-container {
    width: 600px;
    position: absolute;
    left: 25px;
    bottom: 100px;
}

However, .child-container also includes absolutely positioned elements, which are position relatively to .parent-container because .child-container doesn't have position: relative . So my question is, how can I position .child-container 's children relatively to itself, while still keeping it correctly positioned in .parent-container ?

PS Wrapping .child-container in a position: absolute 'd div and making .child-container position: relative should do the trick, but I was hoping for something more... semantic.

However, .child-container also includes absolutely positioned elements, which are position relatively to .parent-container because .child-container doesn't have position: relative.

Incorrect. Absolute positioning is with respect to the nearest ancestor that is positioned , not position: relative . Anything except position: static will make an element positioned. ( position: relative won't move the container out of normal flow so it is used when you want to set a positioning context with no side effects).

Since the parent is position: absolute; they are positioned with respect to that already.

You don't need to change .child-container position to relative in order to set him has "relative" parent. please review this link from MDN about position absolute.

"The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used."

*positioned ancestor is an element with either: relative, fixed or absolute position

Absolutely positioned elements should already be relative to their parent. Here's a demo which shows nested items within absolute positioning

HTML

<div class='parent-container'>
    Parent
    <div class='child-container'>
        1st Child
        <div class='grandchild-container'>
            2nd Child
        </div>
    </div>
</div>

CSS ( color added to illustrate differences )

.parent-container {
    position: relative;
    background: grey;
}
.child-container {
    position: absolute;
    background: red;
    left: 20px;
}
.grandchild-container {
    position: absolute;
    background: yellow;
    left: 20px;
}

jsFiddle

It will look like this

演示 *Notice each position is relative to its parent.

For more info see:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM