Centering HTML Elements with CSS – POFTUT

Centering HTML Elements with CSS

CSS provides centering HTML elements. HTML elements can have different layouts by using CSS. In this tutorial, we will learn how to center text, image, text block elements of HTML with CSS.

Centering Lines Of Text

CSS provides the text-align attributes where it will set the alignment of the text elements. center value can be provided to this attribute to center text elements like below. In this example, we will center text elements like h2and p.

Centering Lines Of Text

Centering Lines Of Text

Centering a Block Of Text Or Image

In some cases, we may need to center not only the given text or letters, completely the block of the text. We can use the margin-left and margin-right attributes by specifying the width of the block. In this example, we will set the margin-left and margin-right attributes as auto and set the width to 12em which will set the body size of the text block.

Centering a Block Of Text Or Image

Centering a Block Of Text Or Image

Centering A Block or An Image Vertically

Up to now we have centered given text or image elements horizontally but we can also center vertically using vertical-align CSS attribute. In this example, we will center given text vertically by providing the middle as value to the vertical-align attribute.

Center An Image

We can also center an image by using margin-left and margin-right CSS attributes. We will provide auto as value to the margin-left and margin-right.

Center An Image

Center An Image

Centering Vertically using Padding

We can use the padding attribute of the CSS in order to center the given text or image vertically.

Centering Vertically

Centering Vertically

Centering Vertically and Horizontally

We can also center the given text or image vertically and horizontally. We will use line-height and vertical-align attributes with different values.

Centering Vertically and Horizontally

Centering Vertically and Horizontally

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)