首页 > 解决方案 > 尽管 CSS 偏移值相同,但差距很小

问题描述

我正在尝试为标题添加一个小的切角效果。它原则上有效,但在某些字体大小下,标题和角落之间存在间隙。这很可能取决于操作系统和浏览器。我在 macOS 10.14.5 上尝试使用 Firefox 67.0.4。在 Safari 中,间隙在其他字体大小下可见。使用浏览器的缩放功能可以改变行为。

h1 {
    background: black;
    position: relative;
    margin-right: 0.6em;
    color: white;
}

h1::after {
    content: "\200b";
    position: absolute;
    border-left: 0.6em solid black;
    border-top: 0.9em solid transparent;
    top: 0;
    right: -0.6em;
    bottom: 0;
}
<h1>Header</h1>

似乎浏览器不会以相同的方式计算相关值。如果我使用10pxformargin-rightright值,那么差距是负的,这让我更加惊讶。

我愿意接受其他实现相同效果的建议,只要被切断的部分是透明的,所以它适用于背景图像。也许有一种方法可以用 svg 或翻译的元素剪辑角落?角应随字体大小缩放。

标签: cssgaps-in-visuals

解决方案


您可以使用从黑色到透明的线性渐变,并通过以下方式获得过渡点calc()

h1 {
    background: linear-gradient(45deg, black calc(100% - 0.6em), transparent calc(100% - 0.6em));
    position: relative;
    margin-right: 0.6em;
    color: white;
    
    
}
<h1>Header</h1>


推荐阅读