简体   繁体   中英

How to make the div's position is relative to a single div?

For example, I have a "position" div, and I have a div called "A", a div called "B". I would like to both "A", "B" 's position is relative to "position" div.

For example, the position div is 100, 100 in absolute value, and A position is "position"'sx - 100, "position"'sy - 100,... that means , it is in 0, 0 in absolute value. B position is "position"'sx + 100, "position"'sy + 100,... that means , it is in 200, 200 in absolute value.

But when the window resize, or position div, move, I would like to let the "A", and "B" follow the "position"'s position. For example, if the "position" at 500, 500. The A position should be 400, 400. And B position should be 600, 600.

How can I let the "A", and "B" position, following the "position" div using css only? Thank you.

The code is something like this, because the "A" and "B" is not in the "position" dom tree, it is different to use the relative / inherit in positioning:

<body>
       <div id="A"></div>
       <div id="position"></div>
       <div id="B"></div>
</body>

to do that... the div A and B should be inside the "position" div. Then "position" div should have position:relative and A, B should be position:absolute . If your "position" div needs to be absolute, then consider using wrapper divs..

when you set position absolute it means that the top, bottom, left and/or right attributes will be relative to the first parent that has position:relative .. by default the body tag is in position relative... see this

now.... if you dont want to insert the A and B into "position".. then you'll need javascript to calculate the current positions and change them..

Good luck

BTW: try using better names for your divs =P its confusing when you try to explain the position of a "position" div

<html>
<head>
<style>
div {
    height: 200px;
    width: 200px;
}
#position {
    position: absolute;
    top: 400px;
    left: 400px;
    background-color: #444;
}
#A {
    position: relative;
    top: -100px;
    left: -100px;
    background-color: #e00;
}
#B {
    position: relative;
    top: -100px;
    left: 100px;
    background-color: #0ee;
}
</style>
<body>
    <div id="position"> position
           <div id="A">A</div>
           <div id="B">A</div>
    </div>
</body>
</html>

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