o7planning

CSS Align Tutorial with Examples

  1. CSS Align
  2. CSS margin:auto
  3. CSS text-align
  4. CSS float

1. CSS Align

There is no general rule for you to align an element, so you have to give a suitable solution depending on the situation. In this post, I will give a few scenarios and solutions to align an element.
Horizontal Align
Horizontal Align means the way in which you makes an element display left, center or right.
Vertical Align
Vertical Align means the way in which you make an element display top, middle or bottom

2. CSS margin:auto

If you have a Block element, for example, <div>, and align it horizontally center, CSS margin:auto is a good solution.
You need to set the width size of an element to a specific number, or a percentage value (%), but it must be less than 100%, which ensures that the element does not occupy the entire horizontal space of element containing it.
And apply CSS margin:auto to it
margin-left: auto;
margin-right: auto;

/* OR:  */

margin: auto;
Note: CSS margin-top:auto and CSS margin-bottom:auto don't act as vertical alignment.
h-align-block-example.html
<!DOCTYPE html>
<html>
<head>
    <title>CSS Align</title>
    <meta charset="UTF-8"/>
    <style>
        .center {
           margin-left: auto;
           margin-right: auto;
           width: 180px;
           border: 3px solid green;
           padding: 10px;
        }
    </style>
</head>
<body>
    <h3>Horizontal Align - Center</h3> 
    <hr/>
    <div class = "center">
         margin-left: auto; <br/>
         margin-right: auto; <br/>
         width: 180px; <br/>
         border: 3px solid green; <br/>
         padding: 10px;<br/>
    </div>
</body>
</html>

3. CSS text-align

The CSS text-align property is used for a block element or a table cell to align horizontally its inline content.
When CSS text-align applies to an element, it works with all the inline contents of this element, for example, text content, child elements such as <span>,. But it doesn't work with the child elements of the current element.

4. CSS float