Make HTML body align center using CSS.

CSS to Align HTML Body in Center

  • CSS
  • 2 mins read

The following is an example of CSS to align the HTML body element in the center.

Example

In the below CSS style, it is aligning the HTML body by setting the margin-left and margin-right property to 20% of the whole width.

<style>
	html {
	background-color: #aaa;
	}
      body {
        background-color: #ddd;
        margin-left: 20%;
        margin-right: 20%;
        border: 1px dotted gray;
        padding: 10px 10px 10px 10px;
        font-family: sans-serif;
      }
    </style>

Complete HTML and CSS Example

<html>

<head>
    <style type="text/css">
        html {
            background-color: #aaa;
        }
        
        body {
            background-color: #ddd;
            margin-left: 20%;
            margin-right: 20%;
            border: 1px dotted gray;
            padding: 10px 10px 10px 10px;
            font-family: sans-serif;
        }
    </style>
</head>

<body>
    <h1>Align Body Element in Center</h1>
    <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
    <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
    <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
    <p>lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum</p>
</body>

</html>

Output

As shown in the featured image of this article.

See also: