StackLite

How to center a div in CSS?
125
I have been trying to center a div for hours and nothing seems to work. I have tried margin: auto, flexbox, and grid. What is the definitive way to center a div both horizontally and vertically?

Here is what I have tried so far:

```html

Centered Content


```

```css
.parent {
/* styles for parent */
}
.child {
/* styles for child */
}
```

Any help would be appreciated!
css
html
flexbox
grid
centering

Suggested Tags (AI)

css
html
flexbox
Asked about 2 years ago
ALAlice Wonderland

3 Answers

95
Using Flexbox is a modern and easy way:

```css
.parent {
display: flex;
justify-content: center; /* Horizontally center */
align-items: center; /* Vertically center */
min-height: 100vh; /* Or any height */
}
```
answered about 2 years ago by
BOBob The Builder
40
CSS Grid also works well:

```css
.parent {
display: grid;
place-items: center;
min-height: 100vh;
}
```
answered about 2 years ago by
CHCharlie Brown
15
For absolute positioning within a relative parent:

```css
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
This is an older method but still useful in some contexts.
answered about 2 years ago by
ALAlice Wonderland