JDS
JDS

Reputation: 16978

Javascript DOM - aligning a text element to the center?

I have a text node attached to a div that I want to position in the middle of the page. These elements are attached to a mainDiv which is like the whole page. Here's the code I'm trying:

title = document.createElement('div');
title.appendChild(document.createTextNode("The big title!"));
title.style.color = "#F5AE20";
title.style.textAlign = "center"; //this is what I'm trying to solve my problem

mainDiv.appendChild(title); 

Unfortunately the title stays on the top left of the page; I want it top centered. EDIT - just to clarify, I would like to do this within Javascript if possible.

Thanks for any help.

Upvotes: 3

Views: 18367

Answers (2)

Sarhanis
Sarhanis

Reputation: 1587

Just from what you've posted, we can't give you a definitive answer.

We need to take into consideration what's defined in your CSS and also the parents of the DIV you're inserting.

Setting the left and right margins to auto, for instance, won't work for a div that doesn't have a defined width, and setting text-align to be center won't work as expected for a div whose width has been constrained.

Here's some example code that definitely works, anyway:

<html>
<head>
<script type="text/javascript">
function displayResult()
{
title = document.createElement('div');
title.appendChild(document.createTextNode("The big title!"));
title.style.color = "#F5AE20";
title.style.textAlign = "center"; //this is what I'm trying to solve my problem

document.getElementById("div1").appendChild(title); 
}
</script>
</head>
<body>

<div id="div1">This is some text.</div>
<br />

<button type="button" onclick="displayResult()">Align text</button>

</body>
</html>

Upvotes: 4

kfiroo
kfiroo

Reputation: 1953

try setting the left and right margins to 'auto'

Upvotes: 1

Related Questions