CSS: Horizontal Align for Centering


A common issue for CSS beginner is to horizontal align text or centering. You know about the vertical-align attribute, and I have written a post on CSS vertical align. You may figure the horizontal equivalent has to be horizontal-align, but that is wrong. In this post I present you 2 methods that can help in your horizontal styling with CSS.

Horizontal Align for Centering a Block Element

Centring block level elements is easy, just define a explicit width value and set margin:0 auto;.

#parent1 {
	width:600px;
	height:200px;
	background: lightpink;
	-moz-box-sizing: border-box;
}
#child1 {	
	background: lightblue;
	width:300px;
	margin:0 auto;
}
Centring block level elements is easy, just define a explicit width value and set margin:0 auto;.
Centring block level elements is easy, just define a explicit width value and set margin:0 auto;.

Now the entire child div (which contains all the code for your page) will be centered within the parent div while all the elements inside the child div will still be aligned left. We centered the child div, but not the text inside child div.

Horizontal Align for Centering inner text content of a Block Element

The text-align property in CSS is used for aligning the inner text content of a block element. It also effects all inline or inline-block elements in that container.

#parent2 {
	width:600px;
	height:200px;
	text-align:center;
	background: lightpink;
	-moz-box-sizing: border-box;
}
#child2 {	
	background: lightblue;
}
The text-align property in CSS is used for aligning the inner text content of a block element. It also effects all inline or inline-block elements in that container.
The text-align property in CSS is used for aligning the inner text content of a block element. It also effects all inline or inline-block elements in that container.

The child inline element in the parent div was effected by the text-align property.

The text-align property in CSS is used for aligning the inner text content of a block element. It also effects all inline or inline-block elements in that container.
The text-align property in CSS is used for aligning the inner text content of a block element. It also effects all inline or inline-block elements in that container.

Additional Resources

Create a centred horizontal navigation

Horizontally Centered Absolute Positioning

text-align

Horizontal and Vertical Centering Using CSS: A Beginner’s Guide

Horizontal Centering

Horizontal centering using CSS fit-content value

CSS: Horizontally Centering DIV of Unknown Width

Leave a Reply

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