Center Align Elements
To horizontally center a block element (like <div>), use margin: auto;
Setting the width of the element will prevent it from stretching out to the edges of its container.
The element will then take up the specified width, and the remaining space will be split equally between the two margins.
Example
.center {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
Note: Center aligning has no effect if the width
property is not set (or set to 100%).
Center Align Text
To just center the text inside an element, use text-align: center;.
Example
.center {
text-align: center;
border: 3px solid green;
}
Center an Image
To center an image, set left and right margin to auto
and make it into a block
element.
Example
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
}
Left and Right Align – Using position
Example
.right {
position: absolute;
right: 0px;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
Left and Right Align – Using float
Another method for aligning elements is to use the float
property:
Example
.right {
float: right;
width: 300px;
border: 3px solid #73AD21;
padding: 10px;
}
The clearfix Hack
Example
.clearfix::after {
content: "";
clear: both;
display: table;
}
Center Vertically – Using padding
Example
.center {
padding: 70px 0;
border: 3px solid green;
}
Example
.center {
padding: 70px 0;
border: 3px solid green;
text-align: center;
}
Center Vertically – Using line-height
Example
.center {
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
}
/* If the text has multiple lines, add the following: */
.center p {
line-height: 1.5;
display: inline-block;
vertical-align: middle;
}
Center Vertically – Using position & transform
Example
.center {
height: 200px;
position: relative;
border: 3px solid green;
}
.center p {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Center Vertically – Using Flexbox
Example
.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
}