CSS Alignment

Horizontal Centering of an Element

To horizontally center an element like a <div>, you can use margin: auto;. This method works when you set the element's width, preventing it from overflowing its container:

.center {
    margin: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

Note: If you don't set the width (or set it to 100%), centering won't work.

Centering Text

To center text within an element, you can use text-align: center;:

.center {
    text-align: center;
    border: 3px solid green;
}

Centering an Image

To center an image, use margin: auto; and place the image inside a block-level element:

img {
    display: block;
    margin: auto;
    width: 40%;
}

Aligning Elements Using Position

You can align elements using position: absolute;:

.right {
    position: absolute;
    right: 0px;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}

Note: Absolutely positioned elements are removed from the normal flow and can overlap other elements.

Aligning Elements Using Float

Another method to align elements is by using the float property:

.right {
    float: right;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}

Note: When aligning elements this way, it's a good idea to pre-define margins and padding for the <body> element to avoid visible differences across browsers.

Vertical Centering Using Padding

One simple way to vertically center content is by using padding on the top and bottom:

.center {
    padding: 70px 0;
    border: 3px solid green;
}

You can combine horizontal and vertical centering using padding and text-align: center;:

.center {
    padding: 70px 0;
    border: 3px solid green;
    text-align: center;
}

Vertical Centering Using Line-Height

Another method to vertically center text within an element is by using line-height:

.center {
    line-height: 200px;
    height: 200px;
    border: 3px solid green;
    text-align: center;
}

If the text spans multiple lines, add the following code:

.center p {
    line-height: 1.5;
    display: inline-block;
    vertical-align: middle;
}

Vertical Centering Using Position and Transform

You can also use position and transform to vertically center content:

.center { 
    height: 200px;
    position: relative;
    border: 3px solid green; 
}

.center p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

More Examples

Center a <div> using margin:

div {
    margin-left: auto;
    margin-right: auto;
    width: 300px;
    background-color: #b0e0e6;
}

Right-align a <div> using absolute positioning:

div {
    position: absolute;
    right: 0px;
    width: 300px;
    background-color: #b0e0e6;
}