【问题标题】:absolute element under relative element leads to bizarre behavior under Firefox相对元素下的绝对元素导致Firefox下的奇怪行为
【发布时间】:2016-09-20 08:32:49
【问题描述】:

此代码在 Chrome 上按预期运行:

请将鼠标悬停在蓝色球上观看动画:

<!DOCTYPE html>
<html>

<head>
  <style>
    .container {
      position: relative;
      width: 100%;
      height: 200px;
      border: thin solid #6D6;
      overflow: hidden;
    }
    h2 {
      position: absolute;
      border-radius: 100%;
      background-color: blue;
      height:100px;
      width: 100px;
      transition:all 1s ease-out;
      margin: auto;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0;
    }
    
    h2:hover {
      height: 300px;
      width: 300px;
    }
  </style>
</head>

<body>
  <div class='container'>
    <h2></h2>
  </div>
</body>

</html>

但在 Firefox 中,中间的球会扩展至底部,我必须设置顶部或底部才能将其恢复到正确位置。有没有办法让它保持在中间而不像在 Chrome 中那样分配顶部和底部值?

【问题讨论】:

    标签: html css firefox css-transitions


    【解决方案1】:

    使用top: 50%transform: translateY(-50%) 在相对定位的容器中间居中块元素的一个很好的技巧。

    需要IE9+

        .container {
          position: relative;
          width: 100%;
          height: 200px;
          border: thin solid #6D6;
          overflow: hidden;
        }
        h2 {
          position: relative;
          border-radius: 100%;
          background-color: blue;
          height: 300px;
          width: 200px;
          margin: auto;
          top: 50%;
          transform: translateY(-50%);
        }
      <div class='container'>
        <h2></h2>
      </div>

    JSFiddle 演示:https://jsfiddle.net/oujab44t/1/

    【讨论】:

    • 这是我不想做的事情,额外的定位。如您所见,chrome 在扩展时将元素保持在中间,而无需任何其他设置。也许这是 Firefox 的默认行为。
    • @RyVan 仅仅因为某些东西在 Chrome 中以某种方式表现,并不意味着这是标准。这个想法是编写在任何地方都运行相同的代码。你在 Chrome 上开发,并抱怨 Firefox 显示的东西不同。如果你一开始是在 Firefox 上开发的,你就不会遇到这个问题。我的建议仍然存在。这是我在很多地方看到的一个很好的做法。这不是黑客攻击。
    • 谢谢伙计,但我只需要知道天气有可能在 Firefox 中做类似的事情。
    • @RyVan 你能改写一下这个问题吗?你到底在追求什么?
    • 在 chrome 中,一旦我将 blueball 元素设置为中间 .. 即使在尺寸增加并同样掩盖顶部溢出和底部溢出后它仍然存在,在这种情况下,我不需要分配边距- top 或 traslation 将元素保持在中间。但是在 Firefox 中它会扩展到底部并且变得古怪,除非我设置边距或定位条件..
    【解决方案2】:
    <head>
      <style>
      .container {
        to;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
      }
      </style>
    </head>
    <body>
      <div class='container'>
        <h2></h2>
      </div>
    </body>
    </html>
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
    猜你喜欢
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多