text-align:center not working

时间:2016-12-14 18:36:14

标签: html css text-align

我试过寻找答案但没有任何效果。我试图对齐一个段落。我很确定没有什么能覆盖CSS中的代码。这是HTML和CSS:

body {
  background-image: url("../../images/pic01.jpg");
  background-repeat;
}
#main {
  background-color: rgb(255, 84, 0);
  width: 75%;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: auto;
  overflow: auto;
  height: 100%;
  color: rgb(255, 255, 255);
}
#center {
  text-align: center;
}
<body id="top">
  <div id="main">
    <p id="center">
      <h1> TEST </h1> 
    </p>
  </div>
</body>

这里的错误是什么?

5 个答案:

答案 0 :(得分:10)

text-align: center会影响纯文本节点以及具有display: inline;display: inline-block;的子元素。您的假设子元素为h1,默认情况下为display: block;。因此,即使允许h1内有p,这仍然无效(例如,如果您将<p id="center">替换为<div id="center">,那么仍然遇到“非工作”的中心)。

p只能有所谓的 phrasing content ,也就是说,只允许某些元素作为段落中的子元素。

使用任何流内容元素(例如h1)会导致“周围”p标记的自动关闭。这就是您的浏览器真正呈现的内容:

<div id="main">
    <p id="center"> </p>
    <h1> TEST </h1> 
</div>

最后一件事,因为你说你是前端问题的初学者:

请勿在CSS中使用#id选择器。总是使用CSS .class es。当你进一步发展时,请在此处阅读原因:http://oli.jp/2011/ids/

答案 1 :(得分:2)

要使text-aling: center工作,您还必须传递margin: auto选项。

答案 2 :(得分:2)

您的HTML无效。 <p>不能包含<h1>。大多数浏览器会尝试通过关闭标题前的段落来纠正错误,然后在其后创建另一个段落。

您可以删除标题或段落,并根据需要使用CSS进行样式设置。

<强> jsFiddle example

答案 3 :(得分:0)

text-align: center提供给#main h1,例如:

#main h1 {
  text-align: center;
}
  

虽然您在<h1>内部使用了<p>,这是一个无效的HTML,并且您的浏览器会在启动<p></p>之前关闭<h1>来处理它。

请看下面的代码段:

#main h1 {
  text-align: center;
}

body {
    background-image: url("../../images/pic01.jpg");
    background-repeat;
}

#main{
    background-color: rgb(255, 84, 0);
    width: 75%;

    margin-left: auto;
    margin-right: auto;
    margin-bottom: auto;
    margin-top: auto;

    overflow:auto;
    height:100%;
    color: rgb(255, 255, 255);
}

#center {
    text-align: center;
}
<html>
    <head>
        <title>HTML PAMOKOS</title>
        <link rel="stylesheet" href="../assets/css/html.css" />
    </head>

    <body id="top">
        <div id="main">
            <p id="center"></p>
            <h1> TEST </h1>
        </div>
    </body>

</html>

希望这有帮助!

答案 4 :(得分:-1)

  body {
        background-image: url("../../images/pic01.jpg");
        background-repeat;
    }

    #main{
        background-color: rgb(255, 84, 0);
        width: 75%;
    
        margin-left: auto;
        margin-right: auto;
        margin-bottom: auto;
        margin-top: auto;
    
        overflow:auto;
        height:100%;
        color: rgb(255, 255, 255);
    }
#center {
    text-align: center;
}
 

h1{
   text-align: center;
}
 <!DOCTYPE HTML>
    
    <html>
	    <head>
		    <title>HTML PAMOKOS</title>
	    	<link rel="stylesheet" href="../assets/css/html.css" />
	    </head>
    
	    <body id="top">
            <div id="main">
                <p id="center"> <h1> TEST </h1> </p>
            </div>
    	</body>
    
    </html>

相关问题