CSS Layout - Horizontal & Vertical Align CSS
- CSS Introduction
- CSS Selectors
- How To Add CSS
- CSS Colors
- CSS Backgrounds
- CSS Borders
- CSS Margins
- CSS Padding
- CSS Height and Width
- CSS Outline
- CSS Text
- CSS Fonts
- CSS Links
- CSS Lists
- CSS Tables
- CSS Layout - The display Property
- CSS Layout - CSS position
- CSS Layout - display: inline-block
- CSS Layout - Horizontal & Vertical Align
- CSS Combinators
- CSS Opacity / Transparency
- CSS Dropdowns
- Image Gallery
- CSS Attribute Selectors
- CSS Counters
- CSS Media Queries
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:
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;
Center an Image
To center an image, set left and right margin to auto
and make it into a block
element:
Left and Right Align - Using position
One method for aligning elements is to use position: absolute;
:
Example
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
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:
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
: