Chrome和Firefox在固定元素CSS上的表现不同

3

I have this html:

<div class="lightbox">          
    <div class="lightbox-content-wrapper">
        <div class="lightbox-content-inner-wrapper">                    
            <div class="lightbox-content">
                <!-- Popup Form -->
                <div class="lightbox-form-wrapper">
                    Test
                </div>
            </div>
        </div>             
    </div>
</div>

同时需要使用以下CSS:

.lightbox {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  background: rgba( 0, 0, 0, .7 ) repeat;
}

.lightbox-content-wrapper {
  background-color: #FFF;
  width: 20%;
  position: fixed;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  display: table;
  text-align: center;
  border: 10px solid #2980B9;
}

这是fiddle链接:http://jsfiddle.net/p2omaw29/1/。我想创建一个居中显示的lightbox。如果您在Chrome和Firefox中打开fiddle,您会看到它们呈现不同的结果。在Chrome中,盒子位于屏幕正中央,而在Firefox中,它位于顶部,好像bottom: 0;规则无效。那么,究竟是什么导致了这种差异?我已经花费了一个小时来调整一些CSS,但没有任何进展。非常感谢!

嘲笑那些浏览器。我的建议是尝试使用jQuery,因为它据说可以解决浏览器之间的这种恶心差异。用JS来处理CSS的事情很糟糕,但是... - JSelser
是的!这真的很糟糕。为什么浏览器不能使用相同的引擎/规则来呈现CSS?!?!我甚至还没有在Opera和IE上进行测试,我预计它们也会有不同的结果。 - maurisrx
left: 0 部分解决了我的问题 :) - Matthias
1个回答

2

将底部和顶部设为零,可以使元素高度为100%。它从最顶端开始,直到最底端结束。 浏览器中结果的差异是由于显示表属性的不同实现而引起的。如果您将其设置为表格单元格,则可以在两个浏览器中看到实际发生的情况。

以下是如何实现元素位于屏幕中心的方法。

.lightbox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #000;
    background: rgba( 0, 0, 0, .7 ) repeat;
}

.lightbox-content-wrapper {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    background-color: #FFF;
    width: 20%;
    text-align: center;
    border: 10px solid #2980B9;
}

http://jsfiddle.net/09euw1by/

请注意,它不适用于Internet Explorer 8及以下版本,您需要为Internet Explorer 9添加前缀。

http://www.w3schools.com/cssref/css3_pr_transform.asp


谢谢您的解释!在测试了您的CSS之后,我尝试删除transform规则,但它没有起作用。我以为只需使用top: 50%;left: 50%;就可以工作。 - maurisrx
前50%和左50%设置元素在中心的起点,但不是元素本身。这就是为什么使用translate(-50%)将其放回每个方向上元素大小的一半,从而使其居中的原因。 - Lain
哦,我懂了。谢谢您的解释! - maurisrx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接