DEV Community

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

Posted on

2 1

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 :)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️