-
Center text within a container
- Use text-align: center;
<div class="container">
<p>Text line in the center</p>
</div>
p {
text-align: center;
}
-
Center a <div> horizontally within a container
- Use margin: 0 auto;
<div class="container">
<div class="inner"></div>
</div>
.inner {
margin: 0 auto;
}
-
Center a <div> horizontally within a flexbox container
- Use justify-content: center;
<div class="container">
<div class="inner"></div>
</div>
.container {
display: flex;
justify-content: center;
}
-
Center a <div> vertically within a flexbox container
- Use align-items: center;
<div class="container">
<div class="inner"></div>
</div>
.container {
display: flex;
align-items: center;
}
The old way:
set position: relative for the parent, position: absolute for the inner, set top: 50%, and a negative margin-top: -[half of the inner height] for the inner.
-
Center a <div> horizontally and vertically within a flexbox container
- Use align-items: center; and justify-content: center;
<div class="container">
<div class="inner"></div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
}
