Center an Image or Text with CSS


Centering web elements used to be done with the center tag way back in the day. However, using center tags is now considered to be wrong html formatting, and it will make any W3C validation service throw a bunch of errors. The correct way to center web elements like an image or text is with CSS, and we will show you exactly how you can do so.

Centering a Text Element with CSS

Centering text with CSS is actually very easy, and can be done in various ways. The most popular way is to use the “text-align” property.

The CSS code above will center any text between paragraph tags. You can also center a block of text more easy by using the “margin-left” and “margin-right” property.

This code will center all the text paragraphs in the textblock div class. With the with property you can specify the width of the centered block.

Centering an image with CSS

If you have an image on your webpage that needs to be centered using CSS, you’re best off by displaying a block around the image, and then center it using the “margin-left” and “margin-right” property. You would do this as follows

These simple pieces of CSS code can be used to center almost anything horizontally. If you want to center text or an image vertically, you can use the following CSS code.

With the “min-height” property you can specify the height of your text or image. The “vertical-align” property will automatically find the middle center between the top and the bottom of your div.


Leave A Reply