【问题标题】:Centering DIV using any means necessary使用任何必要的方法使 DIV 居中
【发布时间】:2013-10-13 11:02:45
【问题描述】:

我知道使用 CSS 使事物居中已经被问过很多次了,我也看过这些,但无论我做什么,我似乎都无法让我的 div 整齐地居中。

我的 div 很简单

<div id="overlay">
   <img src="~/Content/images/loading.gif" id="img-load" />
</div>

我在此下方有一个表格,其中包含一些信息。是的,我知道桌子不是用来安排等的。我知道。

<table id="uploadTable" style="width:100%;">
<tr valign="top">
    <td width="100%">
        something in here
    </td>
</tr>
<tr>
    <td>
        something in here
    </td>    
</tr>

在这个表声明之后,我有一个 jQuery 来实际确定覆盖的宽度和位置。工作正常,但并不总是完美,而且永远不会在我的移动 Android 设备上(总是在 div 所在位置的左边距)。

<script>           
    $table = $("#uploadTable");                

    $("#overlay").css({
        opacity: 0.9       
        // current 'busy' logo has width of 200, so need to offset width by half that.
        ,left:  (($table.outerWidth()- 100)/2)
        });
</script>

我的叠加层的 CSS 是这样的:

#overlay { 
display:none;     
position:absolute; 
background:#fff; 
z-index: 10;  }

因此,我能够使其居中的唯一方法(主要)是使用一些数学运算,如 ("#overlay").css 代码所示。

我尝试的一切总是将图形放在父位置的最左侧 我试过 margin-left: auto;边距右:自动; 我已经用过 jquery.position()

有人看到这里有什么明显错误的地方吗?感谢您的帮助!

【问题讨论】:

  • 您是在谈论这样的模态中心吗?我有一个 CodePen 草图:cdpn.io/BuDLo
  • 我认为它不适用于 Android,因为 div 比屏幕宽,因此您试图设置负向左。 AFAIK 你不能用任何不是position:relative
  • kunalbhat - 谢谢,这正是我想要的!谢谢。

标签: html centering css


【解决方案1】:

来自 Kunalbhat,谢谢!

http://codepen.io/kunalbhat/full/BuDLo

使用两个单独的 div,一个用于叠加层,一个用于位于其顶部的图形。我使用 jQuery.fadeIn & fadeOut 将显示更改为可见/不可见。再次感谢!

这是我的 CSS:

#modal-overlay {
  background: gray;
  opacity: .75;
  display:none;     
  bottom: 0;
  height: auto;
  left: 0;
  position: fixed;
  right: 0;
  top: 0;
  width: 100%;
  z-index:10;
}




#modal-box {
  display:none;     
  background: white;
  bottom: 0;
  height: 200px;
  left: 0;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  z-index:15;
}

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 2016-09-25
    • 2017-05-22
    • 1970-01-01
    • 2013-01-01
    • 2018-02-17
    • 2012-03-12
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多