How to Left, Right, Center Align With CSS

How to Left, Right, Center Align With CSS

Instead of using HTML alignment attributes with the HTML tags that markup text, the best practice for web designers is to move the presentation (alignment options) information to the stylesheet. This article will explain how to align text and how to center larger page elements such as divs.

Instructions

How to Align Text

    1

    To align text within a normal block of text such as a paragraph or a blockquote, use the text-align property.

    2
    Left, right and center aligned text

    The value choices for the test-align property are left, right, center and justify. Since justified text is not very readable on the Web, the illustration only shows left, right and center. In this illustration, each paragraph has a black border to demonstrate the size of the block element on the page if no set width is applied to the element.

    3

    Normally an element is assigned to an id or class. The text alignment of any items in that id or class is set with a rule such as one of these:

    left
    text-align: left;

    right
    text-align: right;

    center
    text-align: center;

How to Center Divs, Wrapper Divs and Body

    4

    You may want to center an entire layout or a large division of a layout. In such cases you use a different CSS technique.

    5

    You apply the CSS rule to the larger element selector you want centered. It might be the body element, a wrapper div or a container div.

    6

    Centering by this method does not affect text alignment. The centered element will retain the default left alignment of text within the centered element.

    7
    A centered layout

    The following is an illustration of an entire body element (with a black border for clarification purposes) centered on a page. A width must be set for the element, then the left and right margins are set to auto. Here's how:

    body
    width: 80%;
    margin-right: auto;
    margin-left: auto;
    border: 1px solid black;

Blog Archive