定位< div>元素在屏幕的中心 [英] Positioning <div> element at center of screen

查看:75
本文介绍了定位< div>元素在屏幕的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在中心放置< div> (或< table> )的屏幕,而不考虑屏幕尺寸。换句话说,顶部和底部上留下的空间应该相等,右和左侧上留下的空间应该相等。

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>

注意

如果< div> 元素(或< table> )与网站一起滚动。只是希望它在页面加载时居中。

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.

推荐答案

简单的方法,如果你有一个固定的宽度和高度:

The easy way, if you have a fixed width and height:

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

请不要使用内联样式!这是一个工作示例 http://jsfiddle.net/S5bKq/

Please don't use inline styles! Here is a working example http://jsfiddle.net/S5bKq/.

这篇关于定位&lt; div&gt;元素在屏幕的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆