【问题标题】:Fixing center alignment with negative margin-left trick for small window使用负边距左技巧修复小窗口的中心对齐
【发布时间】:2013-02-07 05:16:39
【问题描述】:

我有一个以这种方式居中对齐的 div:

<div id="container" style="position:absolute; top:0px; left:50%; margin-left:-500px; width:1000px;"></div>

正如这个解决方案Trying to center div horizontally and vertically in screen 所建议的那样。

问题在于,如果客户端窗口的宽度(在 FF 15.0.1 中尝试过)小于 1000 像素,水平滚动条将不允许显示 div 的左侧。

有没有纯html/css方式解决?

【问题讨论】:

  • 总是需要 1000px 吗?或者可以是宽度:1000px;最大宽度:100%;?
  • 是的,它必须始终为 1000px 宽度。
  • 那么没有。位置:绝对;强制它完全按照你告诉它的那样,并且身体不会扩大到更大的宽度,所以没有地方可以滚动到。
  • 我想我将不得不使用 js...
  • 我更新了代码。检查一下

标签: html css


【解决方案1】:

嗯。您无法调整客户端窗口的大小。
您可以做的一件事是避免左滚动将父 div 的宽度设置为1000px

  <div id="parent" style="min-width:1000px;"> 
      <div id="container" style="position:absolute; top:0px; left:50%;
        margin-left:-500px; width:1000px;"></div>
  </div>   

注意:
您可能需要将 html 和 body 标签的宽度设置为 min-width=100%

更新:

 <html style="min-width: 100%; background-color:Gray;">
 <body style="min-width: 100%; background-color:White;">
 <div id="parent" style="min-width: 1000px; position:relative;">
    <div id="container" style="position: absolute; top: 0px; left: 50%; margin-left: -500px;
        width: 1000px; border: 1px solid red; height: 10px;">
        1 2 3 4 5
    </div>
  </div>
 </body>
 </html>

我错过了position:relative 来描述。此代码正在运行。

【讨论】:

  • &lt;!DOCTYPE html&gt; &lt;html style="min-width:100%;"&gt; &lt;body style="min-width:100%;"&gt; &lt;div id="parent" style="min-width:1000px;"&gt; &lt;div id="container" style="position:absolute; top:0px; left:50%; margin-left:-500px; width:1000px; border:1px solid red; height:10px;"&gt; 1 2 3 4 5 &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; 似乎没有产生结果...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
  • 2011-06-23
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2017-09-27
  • 1970-01-01
相关资源
最近更新 更多