To center a block element horizontally, apply margin: auto; Additionally, setting its width prevents it from extending to the container’s edges. This ensures it occupies the specified width, with the remaining space evenly distributed between the margins.
This div element is centered.
Example
.center { margin: auto; width: 50%; border: 3px solid green; padding: 10px; } |
Note: Center alignment won’t take effect unless the width property is specified (or set to 100%).
To center the text within an element, simply apply the text-align: center; property.
This text is centered.
Example
.center { text-align: center; border: 3px solid green; } |
To center an image, transform it into a block element and set both left and right margins to auto.
Example
img { |
One technique for aligning elements involves using 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.
Example
.right { position: absolute; right: 0px; width: 300px; border: 3px solid #73AD21; padding: 10px; } |
Note: Elements positioned absolutely are taken out of the document’s normal flow, potentially resulting in overlap with other elements.
.right { float: right; width: 300px; border: 3px solid #73AD21; padding: 10px; } |
NOTE: If an element’s height exceeds that of its containing element and it is floated, it may extend beyond the container’s boundaries. To address this issue, the “clearfix hack” can be employed to resolve overflow concerns (refer to the example below). |
Subsequently, we can incorporate the clearfix hack into the parent element to resolve this issue:
Example
.clearfix::after { content: “”; clear: both; display: table; } |
Numerous techniques exist for vertically centering an element in CSS. One straightforward approach involves utilizing top and bottom padding:
I am vertically centered.
Example
.center { padding: 70px 0; border: 3px solid green; } |
For achieving both vertical and horizontal centering, apply padding along with text-align: center:
I am vertically and horizontally centered.
Example
.center { padding: 70px 0; border: 3px solid green; text-align: center; } |
Yet another technique involves utilizing the line-height property with a value matching the height property:
Example
.center { |
In scenarios where padding and line-height aren’t feasible, an alternative approach involves employing positioning along with the transform property:
Example
.center { height: 200px; position: relative; border: 3px solid green; } .center p { margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } |
Flexbox can also be utilized for centering elements. However, it’s worth noting that flexbox lacks support in IE10 and earlier versions:
Example
.center { display: flex; justify-content: center; align-items: center; height: 200px; border: 3px solid green; } |
Tip: You can learn more about Flexbox in our CSS Flexbox Chapter. |