这是我在CSS中创建的按钮的一个孤立示例。它具有带有渐变的 1px 边框和背景渐变。背景渐变作为伪元素实现,以允许其不透明度在悬停时淡出。
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 的显示器之间的呈现方式不同。在 Chrome on Windows 上呈现的按钮的屏幕截图,具有不同的 DPI 比例:
100% DPI 缩放显示器,正确渲染,无间隙。
150% DPI 缩放显示器,显示背景和边框之间的间隙。
175% DPI 缩放显示器,显示背景和边框之间的间隙。
200% DPI 缩放显示器,正确渲染,无间隙。
我已经尝试了几种策略来呈现按钮,但它们都会导致差距:
- 尝试在
border-image
和background-image
上使用渐变而不是linear-gradient
的图像。 - 尝试使用显式div 作为背景渐变而不是伪元素。
- 尝试使用显式div 作为背景渐变而不是伪元素,并且还使用了纯色左右边框以及 ::before 和 ::after 伪元素,顶部和底部边框具有线性渐变背景。
原因?
我会(未经教育的)猜测这是由缩放时的子像素引起的。它不能是像素的一小部分,因此它选择整个像素值;在某些比例下,父项的计算值比给定子项的值大 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>