Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 829
JDS Avatar asked Apr 03 '26 00:04

JDS


1 Answers

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>
like image 152
Sarhanis Avatar answered Apr 04 '26 12:04

Sarhanis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!