Javascript将居中文本放在页面底部

时间:2014-11-17 20:18:55

标签: javascript html ios css

我正在尝试使用javascript在屏幕底部插入一些居中对齐的文字。

到目前为止我已经

    var toInsert = document.createElement("div");
    toInsert.innerHTML = "text to insert";
    toInsert.style.position = "absolute";     
    toInsert.style.bottom = "0px";

这会把它放在屏幕的底部我想要什么,但是当我尝试使用这个

    toInsert.style.textAlign="center";

中心对齐似乎被上面的“绝对”属性覆盖,文本左对齐。

如何将文字放在屏幕底部并让它居中? 感谢。

PS。 javascript不是jquery,用于iOS设备上的UIWebView。

3 个答案:

答案 0 :(得分:1)

确保你的div是100%宽度。

toInsert.style.width = "100%";



var toInsert = document.createElement("div");
toInsert.innerHTML = "text to insert";
toInsert.style.position = "absolute";
toInsert.style.bottom = "0px";
toInsert.style.textAlign = "center";
toInsert.style.width = "100%";
document.body.appendChild(toInsert);




答案 1 :(得分:0)

IMO使用类标识符更容易在CSS中正确定位元素,然后使用javascript添加类。

由于您使用绝对定位,您正在寻找的CSS可能是:

left:50%;

答案 2 :(得分:0)

我在StackOverFlow上进行了快速搜索,这是第一个出现的,我认为你的答案已经存在。

Best way to center a DIV

这是我的Dabblet.com示例