Arenim
Arenim

Reputation: 4247

How to position div at absolute position?

I'm trying to move my div in exact place (in pixels) I want (coordinates should be relative to parent's div).

I've tried to write this:

<body>
    <div id="desk" style="position: absolute; width:400; height:400; background-color:blue;" >
        <div id="cell1" style="position: absolute; left: 51px; top: 1px; width: 48px; height: 48px; color:black; background-color:black;" />
        <div id="cell2" style="position: absolute; left: 1px; top: 51px; width: 48px; height: 48px; color:black; background-color:black;" />
    </div>
</body>

Here are two squares in (51,1) and (1,51) coordinates.

I've expected to get this:

expected

but got this:

enter image description here

Why? What I'm doing wrong and how it can be made properly?

P.S. 'fixed' instead 'absolute' will do the job, but squares are positioned not under parent div and does not respond to scrolling. Is there any way to fix it?

Upvotes: 2

Views: 1463

Answers (4)

user4035
user4035

Reputation: 23759

This works for me:

<div id="desk" style="position: relative; width:400px; height:400px; background-color:blue;" >
    <div id="cell1" style="position: absolute; left: 51px; top: 1px; width: 48px; height: 48px; color:black; background-color:black;"></div>
    <div id="cell2" style="position: absolute; left: 1px; top: 51px; width: 48px; height: 48px; color:black; background-color:black;" ></div>
</div>
  1. Close <div> tags. It thinks, that the 2-nd div is the child of the 1-st.

  2. Use px in width:400px; height:400px;

Upvotes: 2

Paul Aldred-Bann
Paul Aldred-Bann

Reputation: 6020

You need to close your DIV tags properly:

<body>
    <div id="desk" style="position: absolute; width:400; height:400; background-color:blue;" >
        <div id="cell1" style="position: absolute; left: 51px; top: 1px; width: 48px; height: 48px; color:black; background-color:black;"></div>
        <div id="cell2" style="position: absolute; left: 1px; top: 51px; width: 48px; height: 48px; color:black; background-color:black;"></div>
    </div>
</body>

Example fiddle

Upvotes: 2

udidu
udidu

Reputation: 8588

Here is a fiddle: http://jsfiddle.net/GvQ3x/

Close your div (<div></div> instead of <div />) tags, also use px (or anything else) when you want to set your container div size

Upvotes: 1

Quentin
Quentin

Reputation: 944443

You left the end tags off your divs, so cell2 is inside cell1 and thus is positioned with respect to the edges of cell1 and not desk.

You cannot use XML self-closing tag syntax in HTML.

Upvotes: 2

Related Questions