How to Center a Div or Text in CSS

Center a Div

The HTML example

<div class="container" style="height: 200px; width: 100%;">
<div class="child" style="width: 500px; height: 100px;">
I am the child
</div>
</div>

Horizontally Center a Div

Using margin

.container {
}
.child {
margin: 0 auto;
}

Using flex

.container {
display: flex;
justify-content: center;
}
.child {
}

Using position

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

Vertically Center a Div

Using flex

.container {
display: flex;
align-items: center;
}
.child {
}

Using position

.container {
position: absolute;
}
.child {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}

Horizontally and Vertically Center a Div

Using flex

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

Using grid

.container {
display: grid;
place-items: center;
}
.child {
}

Using position

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

Using margin and grid

.container {
display: grid;
}
.child {
margin: auto;
}

Using margin and flex

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

Center Text

The HTML example

<div class="container" style="width: 500px; height: 100px;">
I am the text
</div>

Horizontally Center Text

Using text-align

.container {
text-align: center;
}

Using flex

.container {
display:flex;
justify-content: center;
}

Vertically Center Text

Using height and line-height

center a single line text

.container {
height: 50px;
line-height: 50px;
}

Using table-cell and vertical-align

.container {
display:table-cell;
vertical-align:middle;
}

Using pading-top and padding-bottom

.container {
padding-top: 100px;
padding-bottom: 100px;
}

Using flex

.container {
display:flex;
align-items:center;
}

Horizontally and Vertically Center Text

Using text-align + line-height

Using text-align + table-cell and vertical-align

Using text-align + padding top and bottom

Using flex

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