DEV Community

Cover image for 4 ways to center a component/div in CSS
Dreamy Developer
Dreamy Developer

Posted on

4 ways to center a component/div in CSS

  • Flexbox
  • Grid
  • Margin auto on a flex item
  • Position
/* Using Flexbox */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Grid */
.parent {
  display: grid;
  justify-content: center;
  align-items: center;
}

/* Grid */
.parent {
  display: grid;
  place-items: center;
}

/* margin auto on a flex items */

.parent {
  display: flex;
}
.child {
  margin: auto;
}

/* Using Position */
.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(-50%, -50%); /* OR right: 0; bottom: 0; */
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
manuartero profile image
Manuel Artero Anguita 🟨

Concise post. Love it :)