开发者

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 Javas开发者_开发百科cript if possible.

Thanks for any help.


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>


try setting the left and right margins to 'auto'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜