14

CSS div positioning using coordinates

 4 years ago
source link: https://www.codesd.com/item/css-div-positioning-using-coordinates.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CSS div positioning using coordinates

advertisements

I'm currently coding a simple game in javascript. The game takes place in a div, called #box. And the enemy is a div called #enemy .

       <div id="box">
                <div id="prepend">
                    <div id="hero"></div>
                </div>
                <div id="enemy"></div>
       </div>

Inside this #box the #enemy will move about using a setInterval() function generating random numbers (animating to x, y) . However, when I do this, somehow the point of origin where the coordinates start is at top left hand corner of the window when it should be in the top left hand corner in the #box. This is how I have been trying to generate random numbers to keep the #enemy inside the #box

var test = Math.floor(Math.random() * (1500 - $("#box").offset().left) + 0),
    test2 = Math.floor(Math.random() * (750 - $("#box").offset().top) + 0);

But the problem I obviously have is that it keeps animating outside the #box.

    #box{
    width:640px;
    height:400px;
    float: left;
    background:url(../png/space.jpg);
    margin: 0 0 0 100px;
    }
    #enemy {
    width: 69px;
    height: 50px;
    position: absolute;
    margin: 100px 0 0 100px;
    background:url(../png/target2.png);
    z-index:2;
}


The container div needs to have position: relative. Otherwise the position of the window, or the closest parent element with a relative position will be used in determining the inner div's position. By making the parent have a relative position, the child div will position itself relative to its parent as opposed to relative to the window.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK