Javascript DOM - 将文本元素与中心对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7071831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:51:51  来源:igfitidea点击:

Javascript DOM - aligning a text element to the center?

javascripthtmlcssdomposition

提问by JDS

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:

我有一个文本节点附加到我想放置在页面中间的 div 上。这些元素附加到一个类似于整个页面的 mainDiv。这是我正在尝试的代码:

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.

不幸的是,标题停留在页面的左上角;我想要它顶部居中。编辑 - 只是为了澄清,如果可能,我想在 Javascript 中执行此操作。

Thanks for any help.

谢谢你的帮助。

回答by Sarhanis

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.

我们需要考虑在您的 CSS 中定义的内容以及您要插入的 DIV 的父级。

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.

例如,将左右边距设置为自动对于没有定义宽度的 div 不起作用,并且将 text-align 设置为居中对于宽度受到限制的 div 将不起作用.

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>

回答by kfiroo

try setting the left and right margins to 'auto'

尝试将左右边距设置为“自动”