Daya Web Logo

Using CSS to Center an Element

Written by David Ugale
Published on 6/21/2018

There are two approaches that we commonly use to center an element using CSS. The first approach uses the CSS margin property. The second approach uses absolute positioning and the CSS transform property.

Using margin To Center An Element

In this approach, we center the element by using auto to set the left and right margins. Note that the centered element must have a value set for the width (i.e. 200px) and the element must be set to a block element.
Centered Element
HTML

<div id="container-element">
    <div id="centered-element">
        Centered Element
    </div>
</div>
CSS

#container-element {
    border: solid red 5px;
    float: left;
    height: 200px;
    width: 100%;
}
#centered-element {
    border: solid blue 5px;
    display: block;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    width: 200px;
}

Using transform To Center An Element

Centered Element
HTML

<div id="container-element-2">
    <div id="centered-element-2">
        Centered Element
    </div>
</div>
CSS

#container-element-2 {
    border: solid red 5px;
    float: left;
    height: 200px;
    position: relative; /* important! */
    width: 100%;
}
#centered-element-2 {
    border: solid blue 5px;
    display: block;
    height: 100%;
    left: 50%;
    position: absolute;
    text-align: center;
    transform: translate(-50%, 0);
    -ms-transform: translate(-50%, 0);
    -webkit-transform: translate(-50%, 0);
    width: 200px;
}