Nivetha Nivetha - 2 months ago 14
CSS Question

margin-left for DOM element is not working

I tried to create a dynamic P element with the margin-left as 33px.But it is not working. But the same is working fine when the left is not used(margin) and with static html p element. Why is it so? I've tried with the IE11 and Chrome Version 60.0.3112.113.

<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<meta charset="utf-8">
</head>
<body>
<div id="screenv" style="border:1px solid black;margin: 5px;padding: 5px;width: 300px;height: 300px;"></div></br>
<input id="tb" type="text" style="border:1px solid black;margin: 5px;padding: 5px;width: 300px;" placeholder="Enter your text"></input>
<button onclick="submit()">Submit</button>
<p style="margin-left:33px;">hello</p>//css works fine
<script type="text/javascript">

var you="",screen="",msg="",c_time="",val="",d,h,m,line;
function submit() {

val=document.getElementById("tb").value;
screen=document.getElementById('screenv');

you=document.createElement("div");
you.innerHTML="You:";

screen.appendChild(you);


c_time=document.createElement("p");
d = new Date();
h = d.getHours();
m = d.getMinutes();
c_time.innerHTML = h+":"+m;
c_time.style.display="inline";
c_time.style.color="grey";

msg=document.createElement("p");
msg.innerHTML=val;
msg.style.margin-left="33px";//not working


line=document.createElement("br");

you.appendChild(c_time);
you.appendChild(line);
you.appendChild(msg);
document.getElementById("tb").value="";
}


</script>

</body>
</html>

Answer Source

msg.style.margin-left="33px"; will be interpreted as subtract operator by the Parser. Thus, all CSS properties with dashes are written in camelCase within Javascript.