Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/79.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
Html 即使“正文文本对齐”设置为“中心”,我的div也会向左对齐。(详情如下)_Html_Css - Fatal编程技术网

Html 即使“正文文本对齐”设置为“中心”,我的div也会向左对齐。(详情如下)

Html 即使“正文文本对齐”设置为“中心”,我的div也会向左对齐。(详情如下),html,css,Html,Css,我有一个左对齐的元素,尽管我的身体将文本对齐设置为居中。我进行了实验,并注意到只有当我的在style属性中设置了width时,它才会向左对齐。如何使我的在具有宽度的同时正确对齐 例如: <!DOCTYPE html> <html> <body style="text-align: center"> <div style="width: 200px"> This div aligns to the left. <

我有一个左对齐的
元素,尽管我的身体将
文本对齐设置为
居中。我进行了实验,并注意到只有当我的
style
属性中设置了
width
时,它才会向左对齐。如何使我的
在具有
宽度的同时正确对齐

例如:

<!DOCTYPE html>
<html>
  <body style="text-align: center">
    <div style="width: 200px">
      This div aligns to the left.
    </div>
    <div>
      This div aligns properly.
    </div>
  </body>
</html>

此div向左对齐。
这个div正确对齐。

div
是块级元素,
文本对齐
将文本居中,而不是div本身

改为

<div style="width: 200px;margin: 0 auto">
   This div aligns to the left.
</div>

此div向左对齐。
margin:0 auto
将上下页边距设置为0(必要时更新),并将页边距平均分配到左/右

从技术上讲,第二个
div
也不居中对齐,您之所以看到它居中对齐,是因为
div
占据其父元素的整个宽度,因为它是块级元素,并且其中的文本居中对齐


因为您限制了第一个
div的
宽度
,所以它位于左侧,但是其中的文本仍将居中对齐。

将样式分开解决了这个问题

<html>

<head>
<style type="text/css">
body{
text-align: center;
}
</style>
</head>

  <body>
    <div>
      This div aligns to the left.
    </div>
    <div>
      This div aligns properly.
    </div>
  </body>

</html>

身体{
文本对齐:居中;
}
此div向左对齐。
这个div正确对齐。

将某些内容居中的最佳方法是mani提到的方法,但是您也可以为div的容器设置
文本对齐
属性,并将div的
显示设置为
内联
。div的作用类似于div容器中的文本。就个人而言,我更喜欢使用
margin:0 auto以使事情集中,但知道这不是唯一的方法是很好的

例如:


*正如您所见,我必须添加一个额外的

,因为内联元素不添加换行符。

“文本对齐对它没有任何影响。”它确实有效果!它使文本在div内居中。它不使div居中。。只是澄清一下out@Aziz哎呀!谢谢你指出这一点。更新了答案以反映您的评论。