-3

This question is different from how can I horizontally center an element because I'm seeking to center the entire body. A great answer is provided below.

What directives can I put in <style> body { } to horizontally center the contents?

<!DOCTYPE html>
<html><head>
    <title>center</title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <style>
        body {
            background-color: #FFFFFF ;
            font-family: Helvetica, sans-serif ;
            color: #000000 ;
            font-size: large
        }
    </style>
</head>
<body>
    <table style="border: none; padding: 0">
        <tr><td><svg width="48" height="48">
            <rect width="48" height="48" style="fill:#EA9000"/></svg></td>
            <td><h2>&nbsp;center.html</h2></td>
        </tr>
    </table>
    <p>vorpal text</p>
    <img src="http://clipart-library.com/data_images/383516.jpg" alt="eek">
    <form action=""><input type="submit" value="Submit"></form>
</body>
</html>

Here's the output from the above code:

html output

Hermitian
  • 1
  • 3

1 Answers1

0

You can use flexbox for this. Specifically the flex-direction: column; which renders the contents vertically and align-items: center; which centers the vertically rendered content.

See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more details on flexbox.

<!DOCTYPE html>
<html><head>
    <title>center</title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <style>
        body {
            background-color: #FFFFFF ;
            font-family: Helvetica, sans-serif ;
            color: #000000 ;
            font-size: large;

            /* Start of new styles */
            display: flex;
            flex-direction: column;
            align-items: center;
        }
    </style>
</head>
<body>
    <table style="border: none; padding: 0">
        <tr><td><svg width="48" height="48">
            <rect width="48" height="48" style="fill:#EA9000"/></svg></td>
            <td><h2>&nbsp;center.html</h2></td>
        </tr>
    </table>
    <p>vorpal text</p>
    <img src="http://clipart-library.com/data_images/383516.jpg" alt="eek">
    <form action=""><input type="submit" value="Submit"></form>
</body>
</html>
David Lee
  • 2,040
  • 17
  • 36