Search code examples
csstext-alignmenttext-align

Why is css text-align:center, not centering text? Underlining in the same format is working


I wrote simple CSS to align text using the w3schools example with:

text-align:center

When I add an underline in the same format, the underline works.

Here's the snippet:

.CenterIt {
	text-align:center;
}
.UnderlineIt {
	text-decoration:underline;
}
<span class="UnderlineIt">
<span class="CenterIt">Registration Form</span>
</span>   

Here's the w3schools page (the align text section): https://www.w3schools.com/css/css_align.asp

In my full code I have the text I want to center inside another box. I've tried it both inside that box and outside any boxes. It doesn't center.


Solution

  • .CenterIt {
    	text-align:center;
      display:block;
    }
    .UnderlineIt {
    	text-decoration:underline;
    }
    <span class="UnderlineIt">
    <span class="CenterIt">Registration Form</span>
    </span>

    The display property of span by default is inline. i.e.,

    display:inline;
    

    Therefore, <span> will take only the width of its content. In contrast, block elements like <div>, by default, take the full line (and thereby the full width of the page) for its content.

    To make the text-align work for <span>, you need to change it into a block element.

    Set

    display: block;

    for the span with .CenterIt class. This will make .CenterIt take the full line (and thereby the full width of the page), and then the text-align: center; will centralize the content.