【问题标题】:Box-shadow doesn't fit element's sides盒子阴影不适合元素的侧面
【发布时间】:2015-05-04 07:34:31
【问题描述】:

注意:不要关注此代码的目的,它只是一个极简示例,以突出遇到的问题。

当我使用box-shadow 属性时,它有时不适合元素的边,导致元素与其阴影之间有1px(或更少)的边距。这是一个示例,使用transform 提出问题(我认为这不是唯一的方法):

h1 {
  width: 100px;
  text-align: center;
  margin: 25px 55px;
  background: black;
  box-shadow: 30px 0 0 black, -30px 0 0 black;
  font-size: 24px;
  line-height: 50px;
  /* I use 0.5px to show the bug, I would use n% in real conditions */
  transform: translate(0.5px, 0); 
}
h1 a {
  color: white;
  text-decoration: none;
}
<h1><a href="#">Foo</a></h1>

如果您没有看到任何内容,请尝试查看全屏 sn-p,然后调整您的浏览器大小(我遇到了 Chrome 和 Firefox 的问题)。下面是我制作的几张截图,以及(明显的)预期结果:

有人遇到过这个问题吗?
看起来像浏览器,但我们能找到一种解决方法来避免这些边距吗?

编辑

我发现了一些新的东西:如果我在单边设置一个盒子阴影,那么使用 Chrome 就不会出现间隙(Firefox 仍然存在):

h1 {
  width: 100px;
  text-align: center;
  margin: 25px 55px;
  background: black;
  box-shadow: 30px 0 0 black, -30px 0 0 black;
  font-size: 24px;
  line-height: 50px;
  /* I use 0.5px to show the bug, I would use n% in real conditions */
  transform: translate(0.5px, 20px); 
}
h1 a {
  color: white;
  text-decoration: none;
}
h1:nth-child(2) {
  box-shadow: 30px 0 0 black;    
}
h1:nth-child(3) {
  box-shadow: -30px 0 0 black;    
}
<h1><a href="#">Foo</a></h1>
<h1><a href="#">Foo</a></h1>
<h1><a href="#">Foo</a></h1>

【问题讨论】:

  • transform: translate(0.5px, 0); 的目的是什么?如果删除它会怎样?
  • 想知道一半像素是什么样子的。四舍五入总是一个问题......不是吗?
  • 其目的是确保您能看到错误(无论您的屏幕分辨率如何)。但是我碰巧在翻译中使用了百分比,这导致了同样的错误:transform: translate(25%, 0);
  • 再一次,使用 % 也会导致舍入问题...我很好奇这个 box-shadow 的实际用途。对于一个简单的链接来说,这似乎是一个奇怪的选择。
  • adding a border 为我纠正了这个问题(chrome 40 win7)

标签: html css cross-browser box-shadow


【解决方案1】:

这个 CSS 有效:

h1 {
  width: 100px;
  text-align: center;
  margin: 0px;
  background: green;
  box-shadow: 30px 0 0 black;
  font-size: 24px;
  line-height: 50px;
  /* I use 0.5px to show the bug, I would use n% in real conditions */
  transform: translate(0.5px, 0); 
}
h1 a {
  color: white;
  text-decoration: none;
}

这是Fiddle。 您使用的颜色(黑底黑字)与您看到的略有不同。改变颜色就可以了。

【讨论】:

  • 错了,我还有差距。但我发现你的代码有新的东西。 只有当我在两边都有一个盒子阴影时才会出现间隙(仅限 Chrome)。
  • transform:translate(.5px, 0); 您正在移动 h1 而不是 box-shadow。尝试摆脱transform
【解决方案2】:

使用 Chrome 版本 42.0.2311.90 m

当浏览器分辨率发生变化(从大约 25% 到 500%)并且
平移 y 轴为 0 或 0px
出现差距。示例代码:

    transform: translate(0.5px, 0); 
    transform: translate(0.5px, 0px); 
    transform: translate(7px, 0); 
    transform: translate(7px, 0px);

使用 zessx 的 EDIT,在输出中显示 3 个示例,我得到了与他为

所做的相同的结果
    transform: translate(0.5px, 20px);

但是当我在任一轴上删除一个“px”时,没有间隙。例子:

    transform: translate(0.5px, 20);
    transform: translate(0.5px, 1);
    transform: translate(0.5, 20px); 
    transform: translate(0, 20px); 

zessx

所述,随着 Chrome 中的分辨率变化,间隙移动(从 L 到 R 消失)仅适用于两侧的阴影框

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多