CSS Layout – Horizontal & Vertical Align

Center Align Elements

To horizontally center a block element (like <div>), use margin: auto;

Setting the width of the element will prevent it from stretching out to the edges of its container.

The element will then take up the specified width, and the remaining space will be split equally between the two margins:

This div element is centered.

cc

Note: Center aligning has no effect if the width property is not set (or set to 100%).


Center Align Text

To just center the text inside an element, use text-align: center;

This text is centered.

cc

Tip: For more examples on how to align text, see the CSS Text chapter.


Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Paris

cc


Left and Right Align – Using position

One method for aligning elements is to use position: absolute;:

In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.

cc

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.


Left and Right Align – Using float

Another method for aligning elements is to use the float property:

cc


The clearfix Hack

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the “clearfix hack” to fix this (see example below).

Without Clearfix

With Clearfix

Then we can add the clearfix hack to the containing element to fix this problem:

cc


Center Vertically – Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:

I am vertically centered.

cc

To center both vertically and horizontally, use padding and text-align: center:

I am vertically and horizontally centered.

cc


Center Vertically – Using line-height

Another trick is to use the line-height property with a value that is equal to the height property:

I am vertically and horizontally centered.

cc


Center Vertically – Using position & transform

If padding and line-height are not options, another solution is to use positioning and the transform property:

I am vertically and horizontally centered.

cc

Tip: You will learn more about the transform property in our 2D Transforms Chapter.


Center Vertically – Using Flexbox

You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:

I am vertically and horizontally centered.
cc
Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.

www.w3schools.com

3D Effect

Portal scene

UI Design