How to align entire html body to the center?

Viewed 475891

How do I align entire html body to the center ?

11 Answers

Try this

body {
max-width: max-content;
margin: auto;
}

I use flexbox on html. For a nice effect, you can match the browsers chrome so as to frame your content on screen sizes larger than your page maximums. I find that #eeeeee matches pretty well. You could add a box shadow for a nice float effect.

    html{
        display: flex;
        flex-flow: row nowrap;  
        justify-content: center;
        align-content: center;
        align-items: center;
        height:100%;
        margin: 0;
        padding: 0;
        background:#eeeeee;
    }
    body {
        margin: 0;
        flex: 0 1 auto;
        align-self: auto;
        /*recommend 1920 / 1080 max based on usage stats, use 100% to that point*/
        width: 100%
        max-width: 900px;
        height: 100%;
        max-height: 600px;
        background:#fafafa;
        -webkit-box-shadow: 0px 0px 96px 0px rgba(0,0,0,0.75);
        -moz-box-shadow: 0px 0px 96px 0px rgba(0,0,0,0.75);
        box-shadow: 0px 0px 96px 0px rgba(0,0,0,0.75);
    }

enter image description here enter image description here image/data courtesy StatCounter

Just write

<body>
   <center>
            *Your Code Here*
   </center></body>
<style>
        body{
            max-width: 1180px;
            width: 98%;
            margin: 0px auto;
            text-align: left;
        }
</style>

Just apply this style before applying any CSS. You can change width as per your need.

What about this:

  • if width: 60%, then margin-left: (1-60%)/2 = 20%;
  • if height: 50%, then margin-top: (1-50%)/2=25%;

So do margin-bottom and margin-right;

<style type="text/css">
        html {
            height: 100%;
        }

        body {
            width: 60%;
            height: 50%;
            margin: 25% 20% 25% 20%;
            border: 1px solid;
        }
    </style>

<body class="center">
    <div align="center">
    </div>
</body>

This is the code that worked for me, using glitch.me.

Related