Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center body on a page?

I'm trying to center the body element on my HTML page.

enter image description here

Basically, in the CSS I set the body element to be display: inline-block; so that it is only as wide as its contents. That works fine. However, margin: 0px auto; doesn't center it on the page.

Does anyone know how to fix this? I want the big blue square to be centered on the page, not floating to the left like it is now.

Here's my CSS:

body {     display: inline-block;     margin: 0px auto;     text-align: center; } 
like image 737
Ryan Peschel Avatar asked Jun 03 '12 18:06

Ryan Peschel


People also ask

How do I center a body in HTML?

The <center> HTML element is a block-level element that displays its block-level or inline contents centered horizontally within its containing element.

How do I center everything on a page?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center. In the Apply to box, click Selected text, and then click OK.

How do I center align a body in CSS?

You do this by setting the display property to “flex.” Then, define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I center in the middle of the page?

If you want to do a horizontal centering, just put the form inside a DIV tag and apply align="center" attribute to it. So even if the form width is changed, your centering will remain the same.


2 Answers

    body     {         width:80%;         margin-left:auto;         margin-right:auto;     } 

This will work on most browsers, including IE.

like image 77
Freakishly Avatar answered Oct 10 '22 02:10

Freakishly


Also apply text-align: center; on the html element like so:

html {   text-align: center; } 

A better approach though is to have an inner container div, which will be centralized, and not the body.

like image 41
Madara's Ghost Avatar answered Oct 10 '22 03:10

Madara's Ghost