【问题标题】:css - absolute position from top, horizontally centered divcss - 从顶部开始的绝对位置,水平居中的 div
【发布时间】:2011-08-23 11:46:14
【问题描述】:

我查看了一个 googol 谷歌搜索结果,但没有找到任何工作。

我需要让我的 div(高 333 像素,宽 550 像素)水平居中,并且始终距顶部 275 像素。每次我尝试这样做时,它都会消失。

【问题讨论】:

标签: css css-position centering


【解决方案1】:

如果 div 应该位于顶部,则必须使用 position:absolute。否则,@sdleihssirhc 的答案应该有效。

定位示例

#middlebox
{
    position:    absolute;
    top:         275px;
    left:        50%;    /* move the left edge to the center … */
    margin-left: -275px; /* … and move it to the left half the box’ width. */
    z-index:     9999;   /* Try to get it on top. */
}

使用DragonflyFirebug 等工具检查属性是否仍然消失。

【讨论】:

  • 是的,这非常有效。谢谢!轻微的错字,如果盒子是 550px 宽,左边距应该是 -225,而不是 -275。
  • @captainandcoke 550 / 2 = 275。;)
【解决方案2】:

根据内容和上下文,您可以设置该 div 的边距:

margin: 275px auto 0;

【讨论】:

    【解决方案3】:

    除非您考虑静态定位,否则我认为您根本不需要使用绝对定位。试试这个:

    <html>
    <head>
    <title>Test</title>
    </head>
    <body>
    <div style="width:550px; height:333px; background-color:orange; margin: 275px auto">
    Is this what you want?
    </div>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 2017-06-23
      • 2016-03-04
      • 2013-08-01
      • 1970-01-01
      相关资源
      最近更新 更多