How do you center something in HTML?

I recently talked with a client that had what seemed to be a very basic question:

"How do a center something in HTML?".

I immediate remembered an instance in the past, when I was first starting out, when I had the same problem. It was very frustrating. It seemed, to me, that something as simple as centering should be just as simple to implement as it is to visualize. I eventually realized that the issue was with a few misunderstandings that I had at the time.

First, in order to center anything, you need at least two things:
1) The thing you want centered (obviously), and
2) The container in which you want to center it.

The code that he was using was the following:


  <p>Stuff he didn't want centered</p>
  <br />
  <a href="link"><u>Stuff he wanted centered</u></a>

The problem with this is that both the 'a' tag and the 'u' tag are inline elements, and it is impossible to center inline elements by themselves. You need at least one block-level element, such as <div>, <h1>, or <p> to center anything.

Three methods to centering:

The <center> tag

The first method is the easiest: Just use the HTML block-level tag <center> :


<center>
This text will be centered.
</center>

This creates a block-level element around your text that contains an implicit style of "text-align:center", which brings us to the next method:

The "text-align:center" style attribute

The next method of centering is to use the "text-align:center" style attribute, either inline the element, like this:


<div style="text-align:center;">
This text will be centered
</div>

...or in the style sheet, like this:


<div class="centerme">
This text will be centered
</div>


<!-- and in your css file: -->

.centerme{
 text-align:center;
}

Anything that this block-level element contains will be aligned center, like this:

Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text. Centered text.

Margin:auto

However, what if you wanted the containing text to be left-aligned, but you wanted to place it in the center? For example:

Containing div.

Centered using "margin:0pt auto;"

You can use the "margin:auto;" attribute to achieve this.

<div>
<p style="width:50%;margin:0pt auto;">Centered using "margin:0pt auto;"</p>
</div>

This allows you to center any block-level element that is contained within another block-level element to be centered by the margin alone. The "0pt" is the top/bottom margins, and the "auto" will automatically set the margins to center the element.

Once you understand the nature of block-level elements vs. inline elements, its not too difficult to grasp, but it is understandable to run into issues with this when you are first learning HTML.




Joshua Albert Divider