Search code examples
htmltext-align

The "text-align: center" isn't working in a span element


I haven't done HTML and CSS for a while so I may be forgetting something, but for some reason a "style" tag with the "text-align" property set isn't working even in the simplest context. I'm about to show you the whole, entire file that I have but my problem is only in the two comments I have. Don't worry about the other stuff; it's for a little passion project I'm working on.

So here is the whole file. I have a lot of stuff in it that isn't relevant nor important; just focus on the code in the two comments.

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>JSON Generator</title>
<link rel="stylesheet" href="web_mod.css"></link>
</head>
<body bgColor="#E3E3E3">
<!--Start here-->
<span style="text-align: center">Coded by AnnualMelons</span><br>
<!--Finish here-->
<span style="color: red; background-color: #2CE65A">Use this generator to generate the code required to create a JSON message.<br>
Fill in the blanks to generate the code. The generator will guide you through it as you go along. Have fun!</span>
<script>

</script>
</body>
</html>

The "Coded by AnnualMelons" part is supposed to be in the center but it's not. At least for me it's not.

I know that the other part of the file isn't relevant but I figured I might as well show you as it may be an external problem.

I'm sure I'm just making a silly mistake because I haven't done this for a while, but it's not working... so yeah. I'm using Firefox as my web browser in case that helps.

Thanks!


Solution

  • The <span> Element is, by default, an "inline" element. Meaning unlike block level elements (<div> <h1> <p> etc.) the span only takes up as much horizontal space as its content.

    text-align: center IS working, but you're applying it to an element that doesn't have a width greater than its content (as all block elements do).

    I recommend either changing the span to a <p> element, or specifying the display: block property on your span.

    Here's a JSfiddle to demonstrate that both a <span> with display: block; text-align: center and a <p> with text-align: center; achieve the same effect.

    Hope that helps!