css - 在 Firefox 中居中元素(水平和垂直)失败

标签 css firefox centering

我使用 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>

最佳答案

因为 .centered 的宽度是容器宽度的 100%,而且行内 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(em 是一个相对单位,在这种情况下,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/

关于css - 在 Firefox 中居中元素(水平和垂直)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480548/

相关文章:

html - CSS居中问题

javascript - 确定带有 @font-face 样式的 svg 文本宽度的可靠方法

html - 动画变色下划线效果

css - 将带有 svg 和文本的 div 居中

java - 自定义协议(protocol)处理程序未在 OSX 上传递参数

firefox - 如何检测 Selenium 何时加载浏览器的错误页面

jquery - 将窗口中当前聚焦的行居中?

html - CSS3 过渡搞乱了 webkit 中的字体?

html - 如何使用外部文件覆盖内联 CSS 规则?

javascript - 为什么javascript :void(0) is not working in Firefox