【问题标题】:Odd nitpicky issue with CSS relative positioningCSS相对定位的奇怪挑剔问题
【发布时间】:2010-09-10 09:43:02
【问题描述】:

我今天在整理一个快速的“正在建设”类型的页面时注意到一个不寻常的问题,我正在使用相对定位将文本移动到图像上。 (此页面是由 SO 的离线页面“启发”的,如果您关心的话)

<html>
  <head>
    <title>Bronco Marching Band</title>
  </head>
  <body style="background-color: #888;">
    <div style="text-align: center;">
      <img src="standby.jpg" width="799px" height="600px" alt="Please Stand By"
       title="The Bronco Band website is down for a major upgrade. Please check back later." 
       style="width: 620px; height: 465px; opacity: 0.8;" />
      <div style="color: #C69C6D; font-size: 397%; font-weight: bold; font-family: sans, arial, helvetica; position: relative; top: -300px; left: 0px;">
        PLEASE STAND BY
      </div>
    </div>
  </body>
</html>

似乎是之前相对定位的div所在的区域还在占用空间。即,如果没有定位,它会在 div 所在的图像下方留下空白。

有没有办法解决这个问题?

【问题讨论】:

  • 供以后参考:只需将您的代码缩进四个空格,它不会在帖子或预览中呈现。

标签: html css


【解决方案1】:

相对定位的元素仍然占用空间。您实际上想要一个绝对定位的元素...您只希望它相对于容器绝对定位!

<div style="text-align: center;position:relative; zoom: 1;"> 
  <img src="standby.jpg" width="799px" height="600px" alt="Please Stand By" title="The Bronco Band website is down for a major upgrade. Please check back later." style="width: 620px; height: 465px; opacity: 0.8;" /> 
  <div style="color: #C69C6D; font-size: 397%; font-weight: bold; font-family: sans, arial, helvetica; position: absolute; top: 200px; left: 0px; width: 100%; text-align:center"> 
    PLEASE STAND BY 
  </div> 
</div> 

关键变化:

  • 容器div 具有position: relative 样式集
  • div 具有 position: absolute 样式集,导致其定位在绝对坐标在父中。
  • 我相对于父级的顶部进行定位,并使定位的div 全宽以允许text-align: center 工作。

编辑: 为了让 IE6 能够正确定位,我使用了一种技巧来强制容器 DIV 的布局:zoom: 1 样式。如果不需要支持 IE6,可以省略此项。

测试于:FF3、IE6、Chrome1、Chromium2

演示:http://jsbin.com/uqisa

【讨论】:

    【解决方案2】:

    而不是这样:

    position: relative;
    top: -300px;
    

    试试这个:

    margin-top: -300px;
    

    另外,在您的 &lt;img /&gt; 标记中,您还应该更改此内容:

    width="799px" height="600px"
    

    到这里:

    width="799" height="600"
    

    【讨论】:

    • 糟糕,忘了去掉宽度/高度。我稍后在 CSS 中管理它。
    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2011-06-26
    • 1970-01-01
    相关资源
    最近更新 更多