How to Set the Left and Top CSS Positioning of a DIV Element Dynamically Using JavaScript
Tags: javascript,html,css,position
Problem :
I want to create a div
element manually and later add some CSS styling to it using JavaScript. I created a div
element and changed it's style with JavaScript. The problem is, some CSS styles do not work.
(color
, background
, width
, height
) those properties worked fine but the (zIndex
, top
, left
) properties do not work. I want to know why this happens and how to correct it.
this is my JavaScript code:
function css()
{
var element = document.createElement('div');
element.id = "someID";
document.body.appendChild(element);
element.appendChild(document.createTextNode
('hello this javascript works'));
// these properties work
document.getElementById('someID').style.zIndex='3';
document.getElementById('someID').style.color='rgb(255,255,0)';
document.getElementById('someID').style.background='rgb(0,102,153)';
document.getElementById('someID').style.width='700px';
document.getElementById('someID').style.height='200px';
//these do not work
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';
}
this is my relevant html code
<input type="submit" name="cssandcreate" id="cssandcreate" value="css" onclick="css();"/>
Solution :
The left
, and top
CSS style settings aren't working because you must first set the position
property. If the position
property is not set, setting the left
and top
styles will have no affect. The position
property has these settings:
- static
- absolute
- fixed
- relative
- initial
- inherit
So, try setting the position
property before setting left
and top
:
object.style.position="absolute"
The differences between the position
properties affect how subsequent settings position your elements.