Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text-align: center not working

I have tried searching for answers but nothing worked. I am trying to align a paragraph. I am pretty sure nothing is overwriting code in CSS. Here is the HTML and 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>

What is the mistake here?

like image 331
Nedas Bolevičius Avatar asked Dec 14 '16 18:12

Nedas Bolevičius


People also ask

Why text-Align Center doesn't work?

Short answer: your text isn't centered because the elements are floated, and floated elements "shrink" to the content, even if it's a block level element.

Why is align not working in HTML?

align only works on block level element like div,p etc. In html5, align attribute of img tag is not supported. <center> tag can also have problems. Best way is to use align attribute on a div, p, span or other container and put img inside that.

How do I force align text Center in HTML?

text-align and inline-block Simply add text-align center to parent div and set the child div display to inline-block. This will force our div to behave like inline element and therefore subjected text-align center.


1 Answers

text-align: center affects pure text nodes as well as child elements that have display: inline; or display: inline-block;. Your assumed child element is h1 which by default has display: block;. So even if it were allowed to have an h1 inside a p, this still wouldn't work (for example if you replaced the <p id="center"> by a <div id="center"> you'd still run into "non-working" centering).

p can only have so-called phrasing content, that is, only certain elements are allowed as child elements inside a paragraph.

Usage of any flow content elements (like e.g. h1) results in automated closing of the "surrounding" p tag. So this is what your browser really renders:

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

One last thing, because you said that you're a beginner in frontend matters:

Do not use #id selectors in CSS. Always use CSS .classes instead. When you've progressed alot more, read about the why here: http://oli.jp/2011/ids/

like image 137
connexo Avatar answered Oct 21 '22 03:10

connexo