欢迎您来到,李雷博客 | PHP博客        登录  |  注册

移动端如何实现1px细线的方法

更新:2020-03-10 11:38:36
人气:6690
来源:本站整理
A+

在移动端中,宽度100%,1px的线看起来要比pc端中宽度100%,1px的线粗,

那是因为css中的1px并不等于移动设备(物理像素)的1px。物理像素显示是1个像素代表2个像素,所以出现为2px

所以我们在移动端中为了让1px的线“看起来”苗条些,会采用一些手段。

解决办法

实现1px的线

方法一:transform

在移动端中,我们对宽度100%,1px的线进行改造,将其宽度设为200%,高度不变,之后使用transform对其缩放50%。

.line{      
    width:200% ;
    height:1px ;
    transform:scale(.5) ;
    -ms-transform:scale(.5) ;
    -o-transform:scale(.5) ;
    -webkit-transform:scale(.5) ;
    -moz-transform:scale(.5) ;
    transform-origin:top left ;         
}

这样苗条的线就出现了!

实现1px的边框

方法一:伪类 + transform 

原始border:去掉border,设置相对定位

新border:设置 :before 或者 :after 重做 border ,并使用 transform 的 scale 缩小一半,设置绝对定位 

.scale-1px{
  position: relative;
  width:100px;
  height:100px;
  border:none;
}
.scale-1px:after{
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border: 1px solid #000;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 200%;
  height: 200%;
  -webkit-transform: scale(0.5);
  transform: scale(0.5);
  -webkit-transform-origin: left top;
  transform-origin: left top;}

优点:

所有场景都能满足

支持圆角(伪类和本体类都需要加border-radius)

缺点:

对于已经使用伪类的元素(例如clearfix),可能需要多层嵌套

方法二:-webkit-min-device-pixel-ratio + 媒体查询 

media query对应devicePixelRatio有个查询值-webkit-min-device-pixel-ratio, css可以写成这样
.border { border: 1px solid #999 }
@media screen and (-webkit-min-device-pixel-ratio: 2) {
    .border { border: 0.5px solid #999 }
}
@media screen and (-webkit-min-device-pixel-ratio: 3) {
    .border { border: 0.333333px solid #999 }
}

缺点:

安卓与低版本IOS不适用

实现边框宽度为1px,宽高各为父元素

方法一:伪类 +  transform

.box1 {
            position: relative;
            border: none;
            height: 100px;
            width: 100px;
            text-align: center;
        }
.box1 div::after {
            content: '';
            border:solid 1px aqua;
            position: absolute;
            left: -50%;
            top: -50%;
            bottom: -50%;
            right: -50%;
            -webkit-transform: scale(.5);
            transform: scale(.5);
            box-sizing: border-box;
        }
<div class="box1">
        <div></div>
</div>


推荐的文章
# 发表我的评论
  /     /  
# 最近评论
暂时还没有评论,要不要说点什么?
  Ads by Google
  联系博主
Hello,本博客系统采用PHP和MySql开发,程序开发完全是因为个人爱好,是自己纯手写PHP源代码,未采用任何PHP框架!
QQ:858353007   微信号:lileihot123
网站地图
会员服务
关于我们
QQ:858353007
 
广告服务
加我微信
移动端访问
 
 
Copyright © 2014- 2025 www.mdaima.com All Rights Reserved.
李雷博客,专注PHP经验、PHP教程及PHP源代码开源下载分享的PHP博客!   ICP备案号:京ICP备10202169号-4