Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  28] [ 1]  / answers: 1 / hits: 17391  / 13 Years ago, mon, august 15, 2011, 12:00:00

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.


More From » html

 Answers
237

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>

[#90593] Sunday, August 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nolancampbellc

Total Points: 9
Total Questions: 102
Total Answers: 101

Location: Saint Vincent and the Grenadines
Member since Mon, Jan 16, 2023
1 Year ago
;