CSS: Center element horizontallly

Suppose we have a container with a header in it, and we want to center the header horizontally in the container, and it should be centered in the container even if the width of the contain is changed. We can accomplish this by making margin-left and margin-right to auto and it will center the element relatve to the parent element. For example, here is the html div:

<div id="container-demo">
	<div id="header-demo">Header</div>
</div>

Here is the css for the above div to center the header.

#container-demo
{
	width:200px;
	height:400px;
	background:green;
}
#header-demo
{
	width:150px;
	height:50px;
	background:red;
	margin-left:auto;
	margin-right:auto;
}
Header

Search within Codexpedia

Custom Search

Search the entire web

Custom Search