CSSHorizontal & Vertical Align
Center elements
horizontally and vertically
CSS Centering Elements
With CSS, you can center elements (horizontally, vertically, or both) with several methods, depending on the type of element.
Center Align Block Elements
Usemargin: auto;, to horizontally center a block-level element (like <div>).
Also specify awidth for the element, to prevent it from stretching out to the edges of its container.
Note: Center aligning has no effect on block-level elements if thewidth property is not set (or set to 100%).
Below, the <div> element is centered and has a width of 50% (and the remaining space will be split equally between the left and right margins):
This div element is centered.
Center Align Text
To center the text inside a block-level element, usetext-align: center;.
This text is centered.
Tip: For more examples on how to align text, see theCSS Text chapter.
Center Align an Image
To center an image, setmargin-left andmargin-right toauto, and also turn the image into ablock element:

Center Align with Flexbox
WithCSS flexbox you can center elements, both horizontally and vertically, within a flex container.
A flex container with both thejustify-content and thealign-items properties set tocenter will align the item(s) in the center (in both axis):
Example
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}
Center Align with Grid
WithCSS grid you can center elements, both horizontally and vertically, within a grid container.
A grid container with theplace-items property set to center, will align the item(s) in the center (in both axis).
Example
display: grid;
place-items: center;
height: 200px;
border: 3px solid green;
}
Left and Right Align - Using position
Another method for aligning elements is to useposition: absolute;:
Note: Absolute positioned elements are removed from the normal flow, and can overlap other elements.
This <div> element is positioned to the right, with the position: absolute property.
Example
position: absolute;
right: 0px;
width: 300px;
border: 3px solid green;
padding: 10px;
}
Left and Right Align - Using float
Another method for aligning an element to the left or right, is to use thefloat property:
Example
float: right;
width: 300px;
border: 3px solid green;
padding: 10px;
}
Center Align with position and transform
If you deal with elements of unknown or dynamic dimensions, it is a common technique to useposition: absolute; combined withtransform: translate(); to center an element:
I am vertically and horizontally centered.
Example
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Tip: You will learn more about the transform property in our2D Transforms Chapter.

