chromedude
chromedude

Reputation: 4302

How do you easily center an HTML element on a page with CSS?

I have a form I would like to center directly in the middle of a page. I have this CSS

#form {
         width: 240px;
         height: 100px
         margin: 0 auto;
         display: block;
       }

this only does it horizontally. Is there a way to do it vertically?

Upvotes: 1

Views: 111

Answers (2)

Jason Peacock
Jason Peacock

Reputation: 1821

Not really - you can declare an offset from the top of the page, but think about it for a moment...how tall is a webpage? What does it mean to be centered vertically?

Do you want to be centered relative to the open browser window height? Or centered relative to the height of the page (top of header to bottom of footer, regardless of browser window size).

On preview, the comments on the original post cover this well.

Upvotes: 0

criticerz
criticerz

Reputation: 3407

I might be wrong but if I remember correctly.. this should work:

#form {
     width: 240px;
     height: 100px
     position: absolute; /* make sure this is wrapped by an element with "position: relative" */
     top: 50%;
     left: 50%;
     margin: -50px 0 0 -120px; /* half of the height and width */
   }

If I'm wrong, then you probably have to use javascript.

Upvotes: 1

Related Questions