开发者

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

开发者 https://www.devze.com 2023-02-06 07:15 出处:网络
I have a form I would like to center directly in the middle of a page. I have this CSS #form { width: 240px;

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消