Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在DIV内水平居中对象_Javascript - Fatal编程技术网

Javascript 在DIV内水平居中对象

Javascript 在DIV内水平居中对象,javascript,Javascript,我试图将一个按钮水平居中放置在div中,但运气不佳: var x = document.createElement("div"); // the div container x.style.backgroundColor = "red"; x.style.width = "200px"; x.style.height = "200px"; document.body.appendChild(x); var y = document.createElement("input"); // t

我试图将一个按钮水平居中放置在div中,但运气不佳:

var x = document.createElement("div"); // the div container
x.style.backgroundColor = "red";
x.style.width = "200px";
x.style.height = "200px";   
document.body.appendChild(x);

var y = document.createElement("input"); // the button to be centered inside div "x"
y.type = "button";
y.value = "test button";
y.style.marginLeft = "auto";
y.style.marginRight = "auto";
x.appendChild(y);
我试过做
y.style.textAlign=“center”
“y.style.margin=“auto 0”
。我做错了什么

请执行以下操作:

x.style.textAlign = 'center';
现场演示:

无法单独对齐元素。通过在保存文本行的元素(在本例中为DIV元素)上设置
text align
属性,只能将文本行作为一个整体对齐


请注意这与
垂直对齐
属性有何不同,该属性允许您单独对齐图元。

以下是几种居中方法:

1) div中的任何内容:

<div align="center"> text or smth </div>
文本或smth
2) 对于文本(也可能是图像):

文本
3) 用于帧或图像

<img style="display:block;margin-left:auto;margin-right:auto;" align="center" src="imageee.jpg" />

4) 只要正确定位:

<div style="width:80%;margin-left:10%;"> content </div>
内容

hm?当我将“y”而不是“x”居中时,为什么我要放置x.style.textallign?您正在设置DIV文本行的对齐方式。DIV是文本行的所有者。非常感谢,现在我明白了,这是唯一的方法吗?还是有其他更标准的方法?@user1019031我将为这些CSS定义一个CSS类属性…请参见此处:嗯,最后一个问题,如何使其垂直居中?verticalAlign=“middle?”对x不起作用…我该如何做?
<div style="width:80%;margin-left:10%;"> content </div>