css how to center code example

Example 1: css center image

.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

Example 2: css align center

//HTML
Hello World
//CSS .parent { display: flex; justify-content: center; align-items: center; }

Example 3: css center

/* this will center all children within the parent element. */
.parent {
  display: flex;
  justify-content: center; /* horizontal */
  align-items: center; /* vertical */
}

Example 4: center with css

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Example 5: css vertical center

/*Remove comment to become a better programmer. */
/* No Flexbox */
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* With Flexbox */

.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

Example 6: css centering

// grid

.parent { 
  display: flex;
  align-items: center;
  justify-content: center;
}

//flex box

.parent { 
  display: flex;
  align-items: center;
  justify-content: center;
}

// position

.parent { 
  position: relative;
}

.child {
  position: absolute;
  left: 50%;
  right: 50%;
  transform: translate(-50%, -50%);
}

Tags:

Misc Example