CSS: Center element horizontallly and vertically

Suppose we have a container with a child div in it, and we want to center the div horizontally and verticaally in the container, and it should be centered in the container even if the width or height of the container is changed. For example, here is the html div:

<div id="parent">
    <div id="child">center</div>
</div>

Here is the css for the above div to center the child element horizontally and vertically in the parent element.

#parent{
	width:200px;
	height:200px;
	background:green;
	position:relative;
}
#child{
	width:50px;
	height:50px;
	background:red;
	margin:auto;
	position:absolute;
	top:0px;bottom:0px;left:0px;right:0px;
}
center

Search within Codexpedia

Custom Search

Search the entire web

Custom Search