【问题标题】:Centering an element (horizontal and vertical) fails in Firefox在 Firefox 中居中元素(水平和垂直)失败
【发布时间】:2013-03-07 00:13:23
【问题描述】:

我正在使用Chris Coyier suggested in CSS-tricks 方法将一些内容(双向)置于容器元素内的中心。为了兼容性,我使用语义方法而不是文章中使用的:before 伪元素。出于某种原因,Firefox(在 v.19 for Mac 上测试)失败了,我无法弄清楚正确的修复方法是什么(而 Safari、Opera、IE9 和 Chrome 都可以正常工作)。

我可以检测浏览器并设置一些条件规则,但如果可能的话,我有兴趣在全局范围内修复此问题。

如果你想在不同的浏览器中查看,这是我来自 the modified fiddle I created 的代码。

CSS:

.block {
    text-align: center;
    background: #c0c0c0;
    margin: 20px 0;
    height: 300px;
}
.content-before {
    content:'';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    margin-right: -0.25em; /* Adjusts for spacing */
}
.centered {
    display: inline-block;
    vertical-align: middle;
    padding: 10px;
    background: #f5f5f5;
}

HTML:

<div>
    <div class="block">
        <span class="content-before"></span>
        <div class="centered">
            <h1>Some text</h1>
            <p>But he stole up to us again, and suddenly clapping
            his hand on my shoulder, said&mdash;"Did ye see anything
            looking like men going towards that ship a while ago?"</p>
        </div>
    </div>
</div>

【问题讨论】:

    标签: css firefox centering


    【解决方案1】:

    由于.centered 的宽度是容器宽度的 100%,布局被破坏,并且 inline-block 元素不能很好地处理溢出(它们被推到下一行)。

    尝试为.block 元素设置font-size: 0,然后在.centered 中重新声明字体大小(比如16px)。它对我有用 - http://jsfiddle.net/teddyrised/hJtpF/4986/

    .block {
        font-size: 0;
        /* Rest of the styles here */
    }
    .centered {
        font-size: 16px;
        /* Rest of the styles here */
    }
    

    这里唯一的缺点是您必须使用像素值来重新声明字体大小 - em 单位(我个人最常使用)将不起作用,因为父级的字体大小为 0 (@987654329 @ 是一个相对单位,在这种情况下,em 将引用为 0 的父字体大小,任何乘以零都为零)。

    [编辑]:如果你不想使用这个肮脏的hack,那么你也可以选择确保子容器的宽度.centered不是父容器宽度的100%,这样就有了为空元素 .content-before 留出一些空间,类似于:

    .centered {
        box-sizing: border-box; /* So that padding is also taken into account */
        width: 90%;
        /* Rest of the styles here */
    }
    

    第二个推荐见 fiddle - http://jsfiddle.net/teddyrised/hJtpF/4988/

    【讨论】:

    • 谢谢。不幸的是,字体大小(以 em 为单位)的缺点适用于我的情况。但是,这种肮脏的技巧似乎是最好的方法,因为第二种解决方法会在内容的两侧创建空白空间,当窗口大小调整时也会发生变化。
    • 事实上,CSS hack 变得如此混乱,我通常会选择基于 JS 的方法 :) 当您已经运行 jQuery 时不会产生太多开销。
    • 哦不,我完全忘记了内容的 em 边距和填充:/
    • 我最终将所有 em 转换为必要规则中的像素,并且我坚持使用 0px 方式。再次感谢。
    猜你喜欢
    • 2013-10-27
    • 1970-01-01
    • 2017-02-28
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    相关资源
    最近更新 更多