I recently received an email from a visitor asking me how she could centre ("center" in US English) some text in the middle of a box. This article answers that question, along with related ones that I have been asked over the years about aligning text in the centre of a page.
Note that this article only deals with the specific query mentioned above. It does not deal with how to centre a block (eg a box) on your page without centring ("centering") the text inside. Nor does it address how to centre an image. Please read the articles linked to in the previous two sentences for those situations.
Aligning text is very straightforward, since CSS ("What
is CSS?") provides the text-align
property specifically for this.
For example, the following CSS rule put all headers using the <h1> tag in the middle of the block they are in.
Alternatively, if you only want a particular (say) paragraph to have text aligned in the centre, give it
a class or identifier and set its text-align
property to center
.
For example, if your paragraph has a class of "weeklyhighlights", that is, it has opening tag
of <p class="weeklyhighlights">
, the CSS code to centre it is as follows.
The same goes for those who have a DIV block (or a box) which has words
that you want to centre. Assuming that your DIV block has an id
of "centrethis", that is, the
block has an opening tag of <div id="centrethis">
, the CSS to centre its contents will be:
For those of you who are not able to add CSS code to the <head>
section of your web page or style sheet,
such as people who post using certain blog
software, or those who use a blog host
that doesn't allow you to easily modify the style sheet, you can directly modify the HTML to include the relevant CSS.
Let's say you want to put the following paragraph in the centre of a page or column.
Change the opening <p>
tag to the following:
The rest of the code and words can remain as they are. The HTML code for that block will therefore look like this:
That's it. Yes, it's that simple.
All modern web browsers, and even many old ones such as the
long obsolete IE 6,
support text-align: center
.
Copyright © 2017 Christopher Heng. All rights reserved.
Get more free tips and articles like this,
on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.
Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.
It will appear on your page as:
How to Centre ("Center") Text on Your Web Page with CSS