我正在使用此代码:
如何将信息水平居中?
function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:40%;left:20%;background- color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}
答案 0 :(得分:0)
您可以通过更改以下行来使其居中:
el.setAttribute("style","position:absolute;top:40%;width:100%;text-align:center;background-color:white;");
基本上,摆脱“left:20%”并添加“text-align:center”和“width:100%”。
答案 1 :(得分:0)
你可以将margin: auto
属性应用于它,它应该根据你所处的div来居中。你的函数看起来像:
function tempAlert(msg,duration)
{
var el = document.createElement("div");
// center, and apply an element width of 0
el.setAttribute("style", "margin: auto;width: 0;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}
好的参考here
工作JSFiddle here