1. ホーム
  2. javascript

[解決済み] Positioning <div> element at center of screen

2022-03-14 22:05:40

Question

I want to position a <div> (or a <table> ) element at the center of the screen irrespective of screen size. In other words, the space left on 'top' and 'bottom' should be equal and space left on 'right' and 'left' sides should be equal. I would like to accomplish this with only CSS.

I have tried the following but it is not working:

 <body>
  <div style="top:0px; border:1px solid red;">
    <table border="1" align="center">
     <tr height="100%">
      <td height="100%" width="100%" valign="middle" align="center">
        We are launching soon!
      </td>
     </tr>
    </table>
  </div>
 </body>

Note:
It is either way fine if the <div> element (or <table> ) scrolls with the website or not. Just want it to be centered when the page loads.

解決方法は?

簡単な方法は、幅と高さが固定されている場合です。

#divElement{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
}​

インラインスタイルは使わないでください 以下は動作例です。 http://jsfiddle.net/S5bKq/ .