Signup/Sign In

How to center your website horizontally with CSS

Most people these days want their website to be horizontally centered. It is preferred over left-aligned websites as the layout of the websites looks the same for every device.

In this tutorial, we will learn about the property to CSS property to horizontally center website.

Horizontally centering the website

To make the website horizontally center, the first thing we have to do is to set the CSS max-width property for the parent div element in which the whole code of the website is wrapped. Then add margin: auto to center the container. The margin: auto property will provide equal spacing on the left and right sides of the container.

Example: Center website horizontally with CSS

Here, we have set the max-width: 700px so that the website will center for the larger viewport. We have used background-color to distinguish the website from the screen size.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>HTML </title>
<style>
    body {
	  background-color: #cccccc;
	}
    .container {
	   max-width: 700px; /* resize to max-width to see effect */
	   margin: auto; /* center the website */
	   background-color: white;
	   font-size: 20px;
	   height: 100vh;
	}
}
</head>
</style>
<body>
	<div class="container">
		<h2> Horizontally center website </h2>
		<h3> Resize the browser to see the effect </h3>
		<p> Adding some content </p>
		<p> Adding some content </p>
		<p> Adding some content </p>
		<p> Adding some content </p>		
	</div>	
</body>
</html>

Output

Here is the output of the above code.

Horizontally center website

Example: Centering the website horizontally and vertically

Here, we have defined max-height so that the layout is centered vertically too.

Conclusion

In this tutorial, we have learned to center the website horizontally with CSS. We can center the website horizontally by specifying the CSS max-width property and the margin property with value auto. The margin property with value auto provides equal space to the left and right of the HTML element. When equal space is provided to both sides of the website, then the website will automatically seem horizontally centered.



About the author: