Paul
Paul

Reputation: 385

Absolute positioning in Chrome?

It works in IE/FF but not Chrome.

    html += '<div id = "note" style = "position: absolute; background-color:'
           + newcss[0] + '; margin-left:'
           + newcss[1] + '; margin-top:'
           + newcss[2] +  '; width = 100px; height = 100px;">'
           + newnote + '</div>';

Basically I am adding a new note into the page, with random colors, and position from left and top (stores in newcss).

Pic of IE vs Chrome (IE on left):

https://i.sstatic.net/LFZhD.png

EDIT: Yah that was a mistake; width: and height: fixes it to actually be the right size, but they still are all just pasted on the same spot right under the bar, rather than random spaces

EDIT2: I originally had them as separate ids (I was just messing around with jquery to see something haha)

Upvotes: 0

Views: 5243

Answers (3)

zellio
zellio

Reputation: 32484

The css is incorrect. Css Style rules are in the form key:val; rather than key=vale. Absolute positioning allows you to define top left bottom and right values and places the object at that position ( either relative to the page or to the containing element ( if that element has position:relative set )). Use those for the placement of absolute elements.

Also you should probably be using the DOM objects rather than innerHTML.

var div = document.createElement('div');

div.setAttribute('class', 'note');

div.style.width = '100px';
div.style.height = '100px';
div.style.position = 'absolute';
div.style.backgroundColor = newcss[0];
div.style.top = newcss[1] + 'px';
div.style.left = newcss[2] + 'px';
container.appendChild(div);

Better even yet, defined the stuff that never changes as a style rule and then use the Javascript to only set the dynamic content.

.note {
    position: absolute;
    width: 100px;
    height: 100px;
}

Then all you have to do is set top left and background-color

div.setAttribute('class', 'note');
div.style.backgroundColor = newcss[0];
div.style.top = newcss[1] + 'px';
div.style.left = newcss[2] + 'px';
container.appendChild(div);

Upvotes: 1

icktoofay
icktoofay

Reputation: 129011

Try this instead:

html += '<div class = "note" '
     + 'style="position: absolute; '
     + 'background-color:' + newcss[0] + '; '
     + 'left:' + newcss[1] + '; '
     + 'top:' + newcss[2] + '; '
     + 'width: 100px; height: 100px;">' + newnote + '</div>';

Changes:

  • Changed id to class; it is invalid for two elements to have the same id in one document.
  • Changed margin-left and margin-top to left and top.

Upvotes: 0

mildog8
mildog8

Reputation: 2154

give it css of

top: 0px;
left: 0px;
margin-top: newcss[2];
margin-left: newcss[1];
display: block;

or just

top: 0px;
left: 0px;

Upvotes: 1

Related Questions