Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to center your website horizontally with CSS?
To center your website horizontally with CSS, set a div where all the content of the website will be placed. Align it in a way to center it horizontally. For that, we will use the margin and max-width property.
Syntax
.container {
max-width: value;
margin: auto;
}
Set the Website's Main div
Set a div and within that some elements to make it somewhat look like a sample website −
<div class="main">
<h1>Center website horizontally example</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad nemo, nisi fugiat dolores
quidem ipsam, quisquam sit, quos amet provident accusantium. Ab cumque est ut officia libero,
quis non quidem eaque eligendi iusto numquam, optio magni corrupti, eum ad.</p>
</div>
Style the div to Center Your Website Horizontally
We will style the above div main and use the margin property with the value auto. The max-width is also used to set the maximum width of the main div −
.main {
max-width: 600px;
margin: auto;
background: rgb(70, 32, 240);
color: white;
padding: 10px;
}
Example
Let us see the complete example −
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
background: rgb(255, 238, 0);
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.main {
max-width: 600px;
margin: auto;
background: rgb(70, 32, 240);
color: white;
padding: 10px;
}
p {
font-size: 30px;
font-weight: lighter;
}
</style>
</head>
<body>
<div class="main">
<h1>Center a website horizontally example</h1>
<p>This is a demo paragraph. Ad nemo, nisi fugiat dolores
quidem ipsam, quisquam sit, quos amet provident accusantium. Ab cumque est ut officia libero,
quis non quidem eaque eligendi iusto numquam, optio magni corrupti, eum ad.</p>
</div>
</body>
</html>
A centered purple container with white text appears on a yellow background. The container has a maximum width of 600px and is horizontally centered on the page.
Key Points
The margin: auto property works by automatically calculating equal left and right margins, which centers the element horizontally. The max-width ensures the container doesn't exceed a certain width while remaining responsive.
Conclusion
Centering a website horizontally is easily achieved using margin: auto combined with a max-width property. This method is responsive and works across all modern browsers.
