centering in CSS

  1. Vertical align
  2. Horizontal align
  3. Links

Vertical align

  1. With Transform:
1
2
3
4
5
6
7
.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}

Demo:

works on IE 9+

This method can cause elements to be blurry due to the element being placed on a “half pixel”. A solution for this is to either set its parent element to preserve-3d. Like following:

1
2
3
4
5
6
7
8
9
10
11
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}

.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}

Or, you can set the perspective of the element:

1
2
3
4
5
.element {
position: relative;
top: 50%;
transform: perspective(1px) translateY(-50%);
}
  1. Flexbox
1
2
3
4
5
.flex-container {
display: flex;
align-items: center;
align-content: center; /* this property only takes effect on multi-line flexible containers */
}
  1. inline-hight
1
2
3
4
5
.valign {
line-height: 200px;
margin-top: 0;
margin-bottom: 0;
}
  1. position: absolute && margin: auto;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#container{
width: 1000px;
height: 1000px;
position: relative;
}

#center{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}

Horizontal align

  1. Flexbox
1
2
3
4
.flex-container {
display: flex;
justify-content: center;
}
  1. text-align: center;
1
2
3
.container {
text-align: center;
}

Demo:

3.transform: translateX()

1
2
3
4
5
.halign {
position: relative;
left: 50%;
transform: translateX(-50%);
}

Demo:

  1. margin: auto;
1
2
3
4
.halign {
margin-left: auto;
margin-right: auto;
}

Demo: