Javascript DOM - aligning a text element to the center?

16,508

Solution 1

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>

Solution 2

try setting the left and right margins to 'auto'

Share:
16,508
JDS
Author by

JDS

Updated on June 04, 2022

Comments

  • JDS
    JDS almost 2 years

    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.