高 DPI 显示器上 div 背景和边框之间的间隙变化为 0-1 像素

2023-12-26

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

https://codepen.io/anon/pen/wbYoeo?editors=1100 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 缩放显示器,正确渲染,无间隙。 https://i.stack.imgur.com/ooK61.png

150% DPI 缩放显示器,显示背景和边框之间的间隙。 https://i.stack.imgur.com/iZhCt.png

175% DPI 缩放显示器,显示背景和边框之间的间隙。 https://i.stack.imgur.com/Ny7zT.png

200% DPI 缩放显示器,正确渲染,无间隙。 https://i.stack.imgur.com/xFPnR.png

我尝试了几种渲染按钮的策略,但它们都会导致间隙:

  • 尝试使用image https://i.stack.imgur.com/dKjDi.png用渐变代替linear-gradient在两个border-image and background-image.
  • 尝试使用显式 div 作为背景渐变而不是伪元素。
  • 尝试使用显式 div 作为背景渐变而不是伪元素,并且还使用实心左边框和右边框以及 ::before 和 ::after 伪元素,以及顶部和底部边框的线性渐变背景。

Cause?

我会(未经教育的)猜测这是由缩放时的子像素引起的。它不能是像素的一小部分,因此它选择整个像素值;在某些比例下,父级的计算值比给子级的值大 1px。

解决方法

去掉按钮 div 本身的边框,并将其放在::after伪元素,因此边框和背景都是子元素。现在,边框的缩放比例似乎与背景渐变一致。

Example

.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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

高 DPI 显示器上 div 背景和边框之间的间隙变化为 0-1 像素 的相关文章

随机推荐