How to Center a <div>
PDF Download
Made & Published by: AT Products LLC.
Published on: October 23rd, 2024.
This article contains information on how to center a <code>
using CSS, horizontally and vertically, within HTML. The sole purpose of this article is to annoy Venen Jean, so have fun with this little payback.
Horizontally Aligning
Horizontally aligning a <div>
is more easier than vertically aligning a <div>
.
Auto Margin
A margin sets the space outside the selected element. Setting the element's left and right margin to auto, automatically makes it centered horizontally.
Your code should contain margin-left: auto;
and margin-right: auto;
, and its display
must be set to block
using display: block;
. [1]
Flexbox
You can also use Flexbox to center your <div> using display: flex;
and justify-content: center;
. [4]
Text Center
To center not necessarily a <div>
, but any text, use text-align: center;
for its property. [1]
Vertically Aligning
Vertically aligning a <div>
is harder than horizontally aligning.
Using Position and Transform
Combining position: relative;
for your parent container, and using position: absolute;
, top: 50%;
, and transform: translateY(-50%);
for your child container. This can align the child's container in a vertical direction. [2]
Padding
Top and bottom padding can vertically center text. [1]
Line Height
For line-height
to vertically align text, it must be the same height as the container. If your text is above one line, you can use line-height: 1.5;
on the <p>
tag. [1]
Aligning in Both Directions
This section will show how a <div> can be both horizontally and vertically aligned.
Flexbox
You can use Flexbox to center your <div> using display: flex;
, justify-content: center;
, align-items: center;
, and setting a height
on a parent container. [4]
Using Position and Transform
Combining position: relative;
for your parent container, and using position: absolute;
, top: 50%;
, left: 50%;
, and transform: translate(-50%, -50%);
for your child container. This can align the child's container in all directions. [2]
Padding
Top and bottom padding, combined with text-align: center;
, can horizontally and vertically align text. [1]
Line Height
For line-height
to vertically align text, it must be the same height as the container. You can also combine this with text-align: center;
. If your text is above one line, you can use line-height: 1.5;
on the <p>
tag. [1]