How to make a div centre align using CSS?

In this we will learn how we can center align div section on the web page using CSS? Since we use text-align property for centering text. But for center aligning whole block we use margin properties same property we use in aligning image in center of page.
Submitted by Prerna Saxena, on October 11, 2017

CSS helps in styling of HTML elements. To make div section in center of page we will use margin properties.

We will assume, we had div block as follows:

<div>
	<p>Hello</p>
</div>

At first, you will think text-align property will center the div as: text-align:center;

But, this is wrong it will center only text not whole block of div. For centering div we will use margin property and set value of margin to auto. Margin provides space outside border of element. We provide margin property as follows:

p{
	margin: 10px;
}

It will set 10px space around paragraph content from left, right, bottom and top. If you want different values for left, right, bottom and top then provide it as follows:

p{
	margin-top:10px;
	margin-right:12px;
	margin-bottom:5px;
	margin-left:7px;
}

If you set margin to auto then it will center the div horizontally. It will set margin from all sides equally according to space available on page. To center div using margin, it must contain width property. For responsive page it must contain max-width property, set it as follows:

.div{
	margin:auto;
	width:500px;
}

This piece of code will center align the div on page. But, this won’t work for responsive. For responsive this piece of code works:

.div{
	margin:auto;
	max-width:600px;
}

HTML Code with CSS:

<html>
	<head>
		<title>Center Div</title>
		<style>
			.h1style{
				font-size:30px;
				font-family:Georgia;
				color: #FF5733;
				text-align:center;
				}
				.center-div{
				margin:auto;
				max-width:600px;
				background-color:#800000;
				color:#ffffff;
				padding:10px;
				text-align:center;
				height:400px;
				border:2px solid #ffffff;
				border-radius:3px;
				}
		</style>
	</head>
	<body>
		<h1 class="h1style">Center The Div Using Css</h1>
		<div class="center-div">
			<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
			Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley</p>
		</div>
	</body>
</html>

Result:

how to align a div in center using css?

DMEO

CSS Tutorial & Examples »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.