gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:14 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com