How to center a div?

clock icon

asked 3 months agoAsked

message

2Answers

eye

20Views

Can anybody help me to center a div.

I tried everything but I am not able to center a div.

2 Answers

Can you please provide the code where you encountered the issue 

To center a `div` horizontally and vertically in CSS, there are different methods depending on the layout and the behavior you want. Here are some common ways:

### 1. **Using Flexbox (Horizontal and Vertical Centering)**
This is the most flexible and widely-used method:
```css
.container {
  display: flex;
  justify-content: center;  /* Horizontally centers the div */
  align-items: center;      /* Vertically centers the div */
  height: 100vh;            /* Ensures the container takes full viewport height */
}
.child {
  width: 200px;             /* Set width for the div */
  height: 200px;            /* Set height for the div */
  background-color: lightblue;
}
```
- **`justify-content: center;`** horizontally centers the `div`.
- **`align-items: center;`** vertically centers the `div`.

### 2. **Using CSS Grid (Horizontal and Vertical Centering)**
CSS Grid also allows simple centering:
```css
.container {
  display: grid;
  place-items: center;
  height: 100vh;
}
.child {
  width: 200px;
  height: 200px;
  background-color: lightblue;
}
```
- **`place-items: center;`** centers the child both horizontally and vertically.

### 3. **Using `margin: auto` (Horizontal Centering Only)**
To center a `div` horizontally only, use `margin: auto` with a defined width:
```css
.child {
  width: 200px;
  margin: 0 auto;
  background-color: lightblue;
}
```
- This method requires the `div` to have a defined `width`.

### 4. **Absolute Positioning (Horizontal and Vertical Centering)**
You can use absolute positioning with transform for centering:
```css
.container {
  position: relative;
  height: 100vh;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background-color: lightblue;
}
```
- **`top: 50%` and `left: 50%`** place the element's top-left corner at the center.
- **`transform: translate(-50%, -50%)`** adjusts the element back to its center point.

Each method is useful in different scenarios, but Flexbox and Grid are the most modern and widely adopted techniques.

Write your answer here

Top Questions