高分辨率显示器上div背景和边框之间的0-1像素间隙变化问题

7
这是我在CSS中创建的一个按钮的独立示例。它具有带渐变的1像素边框和背景渐变。背景渐变被实现为伪元素,以允许在悬停时淡化其不透明度。

https://codepen.io/anon/pen/wbYoeo?editors=1100

.Button
{
  width: 200px;
  height: 30px;
  cursor: pointer;
    padding: 0.8rem;
    border-style: solid;
    border-image: linear-gradient(
        to right,
        green 0%,
        blue 100%);
    border-image-slice: 1;
    border-width: 1px;
    position: relative;
  margin-top: 10px;
    transition: color 0.2s;
}

.Button::before
{
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-image: linear-gradient(
        to right,
        green 0%,
        blue 100%);
    opacity: 0.5;
    transition: opacity 0.2s;
}

该按钮在不同DPI的显示器上呈现效果不同。以下是在Windows上使用Chrome渲染的按钮截图,DPI比例不同:

100% DPI缩放的显示器,正确呈现且没有间隙。

150% DPI缩放的显示器,背景和边框之间有间隙。

175% DPI缩放的显示器,背景和边框之间有间隙。

200% DPI缩放的显示器,正确呈现且没有间隙。

我尝试了几种策略来呈现该按钮,但它们都会导致间隙出现:

  • 尝试使用带有渐变的image代替linear-gradient用于border-imagebackground-image
  • 尝试使用显式
    来创建背景渐变,而非伪元素。
  • 尝试使用显式
    来创建背景渐变,而非伪元素,并且对于上下边框使用具有线性渐变背景的实心左右边框和::before和::after伪元素。
1个回答

5

原因?

我猜测这可能是由于缩放时的子像素引起的。它不能是一个像素的一部分,所以选择一个整个像素值;在某些比例尺下,父元素的计算值比赋给子元素的值大 1px。

解决方法

将按钮 div 的边框去掉,将其放在伪元素 ::after 上,使边框和背景都成为子元素。现在,边框似乎与背景渐变一致地缩放。

示例

.Button {
  width: 200px;
  height: 30px;
  cursor: pointer;
  padding: 0.8rem;
  position: relative;
  margin-top: 10px;
  transition: color 0.2s;
}

.Button::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-image: linear-gradient( to right, green 0%, blue 100%);
  opacity: 0.2;
  transition: opacity 0.2s;
}

.Button:hover::before {
  opacity: 0.5;
}

.Button:active::before {
  opacity: 1;
}

.Button::after {
  content: '';
  border-style: solid;
  border-image: linear-gradient( to right, green 0%, blue 100%);
  border-image-slice: 1;
  border-width: 1px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

html {
  height: 100%;
  display: table;
  margin: auto;
}

body {
  background: black;
  display: table-cell;
  vertical-align: middle;
  color: white;
  font-family: sans-serif;
}
Click it:
<div class="Button"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接