Center align HTML element with CSS3

CSS 3

Web pages composes of different components and elements. All those components play important role in page composition in terms of users accessibility, UI and UX. Each components are designed to place in position in the page and positioned in relative or absolute to peer elements. We can horizontally align right or align left the relatively positioned components with float property in CSS. Center align defining margin properties as auto for left and right margin. But horizontally center align absolutely positioned components might be tricky unless we have fixed width component.

We can achieve that for fixed width components by defining the left position. Then compenciate the left shift with negative margin as foillows.

div{
position:absolute;
left:50%;
width:500px;
margin-left:-250px; /* half of the width of the element including border width if exists */
}

But what if we have element with dynamic width. Say, content of the element may be lengthy sometimes and short other times. We cannot absolute position such elements using negative margin.

For such case, we can use the translate property (translat-X) of CSS3 to center align the absolute positioned element.

div{
position:absolute;
left:50%;
transform: translatex(-50%);
display:block;
}

Here, we first positioned the element to 50% from left. Then translate element left to 50% of the width of the element. Finally, this brings our element to the center of the page horizontally. This works for any abolutely positioned element with any length.

 

You May Also Like