Centering text and divs in HTML
One of the most asked questions regarding HTML is about centering elements in the page.
For text, in general the most common way is by using some inline CSS code, like this:
<p style="text-align:center">My text</p>
The style attribute allows you to add CSS code on a single HTML tag, and it will generally override the CSS code from separate CSS files, unless you use the !important declaration.
Of course this doesn't always work for all elements, because it can depend on their position on the document.
So here is how to center a DIV and also its text content:
<div style="margin:0 auto; max-width:50%; text-align:center"><p>My text</p></div>
The key part here is the "margin". The "0 auto" value is a shorthand to give a value of zero to margin top and bottom, and a value of auto to the left and right. The max-width is needed because by default the DIV element will take 100% of your space, since it is a block element, but you can use other values, for example max-width:500px or just give it a fixed width using width:500px.
Here is a more specific example for you to make a test:
<div style="background-color:red; padding:20px;">
<p style="margin:0 auto; background-color:orange; padding:20px; max-width:30%;">My text centered in the parent, but not centered in itself</p>
</div>
In this case, the paragraph will be centered to its parent's div, but the text will not be aligned in the center. This is because the text-align property will align your text in the center of the element, like on a Word or Writer document, while the margin auto on the left and right sied will take care of centering our paragraph in the parent's space.
Join our Facebook group DevHub and ask for support on coding topics!
Horizontal Centering with Flex
To center an item horizontally within a flex container, use justify-content: center; on the parent div.
<div style="display: flex; justify-content: center;">
<p>This is centered horizontally with Flexbox.</p>
</div>
Vertical Centering with Flex
To center an item vertically within a flex container, use align-items: center; on the parent div.
<div style="display: flex; align-items: center; height: 200px;">
<p>This is centered vertically with Flexbox.</p>
</div>
Centering with Grids
CSS Grid is another modern layout system that offers a simple way to center items. You can center a single item within a grid container by using place-items: center;.
<div style="display: grid; place-items: center; height: 200px; border: 1px solid black;">
<div>This div is centered with CSS Grid.</div>
</div>
The CSS place-items shorthand aligns items along both the block and inline directions at once. It sets the values of the align-items and justify-items properties. If the second value is not set, the first value is also used for it.
If this guide was useful, follow me on Facebook and subscribe on Youtube!
Also read: