WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

CSS layout-horizontal & vertical align


Horizontal & vertical center align


Center Align - Using margin

To align an element horizontally (such as <div>), use margin: auto ;. Setting to the width of the element will prevent it from overflowing to the edge of the container. The element is specified by specifying the width, and the empty margins on both sides are evenly distributed:

Example

.center { margin: auto; width: 50%; border: 3px solid green; padding: 10px; }
Try it yourself »

Note: If the width attribute is not set (or set to 100%), center alignment will not work.


Left and Right Align - Using position

We can use the position: absolute; property to align elements:

Example

.right { position: absolute; right: 0px; width: 300px; border: 3px solid #73AD21; padding: 10px; }
Try it yourself »
Note: Absolutely positioned elements are removed from the normal flow and can overlap elements.

Tip: When using position to align elements, the <body> element usually sets margin and padding. This prevents visible differences in different browsers.

There is a problem with IE8 and earlier when using the position property. If the container element (<div class = "container"> in our case) is set to the specified width and the! DOCTYPE declaration is omitted, IE8 and earlier will add a 17px margin to the right. This seems to be space reserved for the scroll bar. When using the position property, always set the! DOCTYPE declaration:

Example

body { margin: 0; padding: 0; } .container { position: relative; width: 100%; } .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; }
Try it yourself »

Left and Right Align - Using float

We can also use the float property to align elements:

Example

.right { float: right; width: 300px; border: 3px solid #73AD21; padding: 10px; }
Try it yourself »

Example

body { margin: 0; padding: 0; } .container { position: relative; width: 100%; } .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; }
Try it yourself »