How to center your website horizontally with CSS?

In this tutorial, we will learn how to center a website horizontally with CSS, and how to horizontally center a block element? By Apurva Mathur Last updated : July 23, 2023

Answer: Use CSS margin: auto; Property

You may have observed that many website's content is centrally organized. Even this website is centrally organized. People usually prefer this style because then the right and left side can be used for extra information, most commonly it is used to provide commercials. According to some survey's it is always a good practice to center your website content, as user's don't get bored from the content.

To horizontally center a block element (like <div>), use margin: auto;

Centering your website horizontally

To center your website, you just need to provide the max-width according to your preference (here max-width is set to 800px) and use the margin property with value auto. This will easily center your website as well as you can easily distinguish between the main body and the content body. All of the other properties can be set according to your creativity.

Example to center your website horizontally

<!DOCTYPE html>

<html>
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <style>
         .center {
         max-width: 800px;
         margin: auto;
         background: darkseagreen;
         color: white;
         padding: 10px;
         }
         p {font-size: 36px;font-weight: lighter;}
      </style>
   </head>
   <body style="background: whitesmoke;font-family:'Arial Rounded MT Bold';">
      <div class="center">
         <h1 style="text-align: center;">INCLUDE HELPS EXAMPLE</h1>
         <p>As we now know that we can not buy happiness with money and there is no other shortcut to happiness. <br>It is something that you feel from within.
            In addition, true happiness comes from within yourself.Happiness is basically a state of mind.Moreover, it can only be achieved by being positive and avoiding any negative thought in mind. And if we look at the bright side of ourselves only then we can be happy.
            True happiness means the satisfaction that you find worthy. The long-lasting true happiness comes from life experience, a feeling of purpose, and a positive relationship.
         </p>
      </div>
   </body>
</html>

The output of the above example is:

Example: Center your website horizontally

CSS Examples »



Comments and Discussions!

Load comments ↻





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