CSS; Horizontal Centering
With CSS now available to do the job, the old-time HTML center
tag to center anything or everything was obfuscated. The obfuscation took place years ago. Even so, it still works for some browsers.
With CSS, centering is of two types.
-
Centering some content. Content would be text, images, videos, or so forth. Centering is accomplished with the
text-align:center;
CSS declaration. -
Centering a container. Containers are divs, tables, paragraphs, and other
display:block
anddisplay:table
containers that contain (or can contain) content. Centering is accomplished by setting bothmargin-left:auto;
andmargin-right:auto;
CSS declarations.
Here is a style sheet for the two types of CSS centering.
<style type="text/css"> .center-content { text-align:center; } .center-container { margin-left:auto; margin-right:auto; } </style>
This illustration displays both types.
A centered line.
Below is the source code of the above illustration.
<style type="text/css"> .center-content { text-align:center; } .center-container { margin-left:auto; margin-right:auto; } </style> <div class="center-container" style="width:200px; border:1px solid #ccc; padding:.75em; border-radius:.5em;"> <p class="center-content"> A centered line. </p> </div>
With those two CSS rules, you'll be prepared to do horizontal centering as you need it for content and containers.
(This content first appeared in Possibilities newsletter.)
Will Bontrager