Home Centering all the things with CSS
Post
Cancel

Centering all the things with CSS

Here are some quick ways to center most items in CSS.

Centering Text

Text has its own property for centering.

1
2
3
.my-div {
    text-align: center;
}

Centering block elements

Block elements can be centered automatically by using margin: 0 auto;.

It’s not very intuitive, but it has been the standard way of centering block elements for a long time now.

Horizontally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div class="container">
  <div class="green"></div>
</div>


.container {
  width: 100%;
  height: 100%;
}

.green {
  background-color: green;
  width: 20%;
  height: 200px;
  margin: 0 auto;
 }

Vertically

1
2
3
4
5
6
7
8
9
10
11
.green {
  background-color: green;
  width: 20%;
  height: 200px;

  /* Use this with 'margin: 0 auto;' in order
     to position within the middle of an element */
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Centering absolutely positioned elements

Here’s a trick for centering absolutely positioned elements (it will also work for fixed).

Horizontally

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<div class="container">
  <div class="green"></div>
</div>


.container {
  width: 100%;
  height: 100%;
  position: relative;
}

.green {
  background-color: green;
  width: 20%;
  height: 200px;

  position: absolute;
  left: 50%;
  transform: translateX(-50%);

  /* For centering from the right -
       right: 50%;
       transform: translateX(50%); */
 }

Vertically

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.green {
  ...

  top: 50%;
  transform: translateY(-50%);

  /* Vertically aligning from the bottom -
       bottom: 50%;
       transform: translateY(50%); */

  /* Aligning the middle -
       left: 50%;
       top: 50%;
       transform: translateX(-50%) translateY(-50%); */
}

Vertically aligning text next to an image

This is easily accomplished by the vertical-align property.

1
2
3
img {
  vertical-align: middle;
}

Any text contained within the same parent will be placed in the center next to the image.

This post is licensed under CC BY 4.0 by the author.