1px问题

为了适配各种屏幕,我们在写代码时一般使用设备独立像素来对页面进行布局。

而在设备像素比大于1的屏幕上,我们写的1px实际上是被多个物理像素渲染,这就会出现1px在有些屏幕上看起来很粗的现象。下面是本人收集到的5个处理方法:

1.border-image

基于media查询判断不同的设备像素比给定不同的border-image:

.border-1px{
    border-bottom: 1px solid #000;
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
    .border-1px{
        border-bottom: none;
        border-width: 0 0 1px 0;
        border-image: url(1px_line.png) 0 0 2 0 stretch;
    }
}

2.background-image

和border-image类似,准备一张符合条件的边框的背景图,模拟在背景上:

.border-1px{
    border-bottom: 1px solid #000;
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
      .border_1px{
           background: url(1px_line.png) repeat-x left bottom;
           background-size: 100% 1px;
      }
}

上面两种都需要单独准备图片,而且圆角不太好处理,但是可以应对大部分的场景

3.伪类+transform

基于media查询判断不同的设备像素对比线条进行缩放

.border-1px:before{
    content: '';
    position: absolute;
    top: 0;
    height: 1px;
    width: 100%;
    background-color: #000;
    transform-origin: 50% 0%;
}
@media only screen and (-webkit-min-device-pixel-ratio:2){
    .border-1px:before{
        transform: scaleY(.5);
    }
}
@media only screen and (-webkit-min-device-pixel-ratio:3){
    .border-1px:before{
        transform: scaleY(.33);
    }   
}

这种方式可以满足各种场景,如果要满足圆角的话,只需要给伪类也加上border-radius即可

4.svg

上面我们border-image和background-image都可以模拟1px边框,但是使用的都是位图,还是需要外部引入。

借助PostCSS的postcss-write-svg我们能直接使用border-image和background-image创建svg的1px边框:

@svg border-1px {
    height: 2px;
    @rect {
        fill: var(--color, black);
        width: 100%;
        height: 50%;
    }
}
.example {
    border: 1px solid transparent;
    border-image: svg(border-1px param(--color #00b1ff)) 2 2 stretch;
}

编译后:

.example {
    border: 1px solid transparent;
    border-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='2px'%3E%3Crect fill='%2300b1ff' width='100%25' height='50%25'/%3E%3C/svg%3E") 2 2 stretch;
}

这种方案是大漠在他的文章中推荐使用的,基本可以满足所有使用场景,而且不需要外部引入。

5.设置viewport

通过设置缩放,让css像素等于真正的物理像素。

例如:当设备像素比为3时,我们将页面缩放1/3,这时1px等于一个真正的屏幕像素:

const scale = 1 / window.devicePixelRatio;
    const viewport = document.querySelector('meta[name="viewport"]');
    if (!viewport) {
        viewport = document.createElement('meta');
        viewport.setAttribute('name', 'viewport');
        window.document.head.appendChild(viewport);
    }
    viewport.setAttribute('content', 'width=device-width,user-scalable=no,initial-scale=' + scale + ',maximum-scale=' + scale + ',minimum-scale=' + scale);

实际上,上面这种方案是早先flexible采用的方案。

当然,这样做是要付出代价的,这意味着你页面上所有的布局都要按照物理像素来写。这显然是不现实的,这时,我们可以借助flexiblevw、vh来帮助我们进行适配。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值