Note: In CSS3 flexbox is way more powerful then below methods. Learn more about flexbox here .
Horizontal Content Centering
The most common and (therefore) easiest type of centering is that of lines of text in a paragraph or in a heading. CSS has the property named text-align for that. The text-align property describes how inline-level content of a block container is aligned. We write it like -
p { text-align: center; }
More values for this property are:
- For left alignment of inline-content
- For center alignment of inline-content
- For right alignment of inline-content
- For stretches spaces and words in inline boxes.
- Takes parents property value
But the problem is this property specially works for ‘text’ type contents.
But if you want centered align of any content on a container, you just can use this piece of code.
Say, we want centered align a image on a container.
See the Pen CSS-Centering things Vertically & Horizontally by Md. Nadimozzaman Pappo (@mnpappo) on CodePen.
Vertical Content Centering
This is the most critical part. We can use the property vertical-align: middle
for contents on a table. But for other contents its usually cause problem. I found this great solution at last. Lets have a look -
For a document that looks like this: (Example taken from W3C)
the style sheet looks like this:
What happened there & how to:
- Make the container relatively positioned, which declares it to be a container for absolutely positioned elements.
- Make the element itself absolutely positioned.
- Place it halfway down the container with
top: 50%
. (Note that 50%’ here means 50% of the height of the container.) - Use a translation to move the element up by half its own height. (The ‘50%’ in ‘translate(0, -50%)’ refers to the height of the element itself.)
See the Pen CSS-Centering things Vertically & Horizontally-2 by Md. Nadimozzaman Pappo (@mnpappo) on CodePen.
This works for any type of content. You can use the property height: auto;
for flexible height. In that case the content will be centered vertically against the height of the container.
Here are some more links given for more awesome examples & guides :
- http://www.w3.org/Style/Examples/007/center
- http://www.w3.org/TR/css-align-3/#overview
- http://www.w3schools.com/cssref/pr_pos_vertical-align.asp
Republished from: My old blog