Centering things without align and center tags
Written on 05/09/20 at 06:19:46 EST by admin
JavascriptingA common task for CSS is to center text or images. In fact, there are three kinds of centering:

Centering lines of text
The most common and (therefore) easiest type of centering is that of lines of text in a paragraph or in a heading. CSS has the property 'text-align' for that:
P { text-align: center }
H2 { text-align: center }
renders each line in a P or in a H2 centered between its margins

Centering a block or image
Sometimes it is not the text that needs to be centered, but the block as a whole. Or, phrased differently: we want the left and right margin to be equal. The way to do that is to set the margins to 'auto'. This is normally used with a block of fixed width, because if the block itself is flexible, it will simply take up all the available width. Here is an example:
P.blocktext {
   margin-left: auto;
   margin-right: auto;
   width: 8em
}

<P class="blocktext">This rather…

This is also the way to center an image: make it into block of its own and apply the margin properties to it. For example:
IMG.displayed {
   display: block;
   margin-left: auto;
   margin-right: auto }

<IMG class="displayed" src="…" alt="…">

Centering vertically
CSS level 2 doesn't have a property for centering things vertically. There will probably be one in CSS level 3 (see below). But even in CSS2 you can center blocks vertically, by combining a few properties. The trick is to specify that the outer block is to be formatted as a table cell, because the contents of a table cell can be centered vertically.
The example below centers a paragraph inside a block that has a certain given height. A separate example shows a paragraph that is centered vertically in the browser window, because it is inside a block that is absolutely positioned and as tall as the window.
DIV.container {
   min-height: 10em;
   display: table-cell;
   vertical-align: middle }

<DIV class="container">
 <P>This small paragraph…
</DIV>

Hope this helps you stacey

News and Comments Brought to you by: Geeks and Bloggers
The comments are owned by the poster. We aren't responsible for its content.