css圆角不圆和1px方案

时间:2023-03-10 04:49:53
css圆角不圆和1px方案

1.圆角不圆

比如需要我们画一个 r 为 5px 的圆,如果我们使用 rem 作为单位,我们很快会发现在一些机型上的图案不圆,会呈现椭圆形。这是由于 rem 转 px 会存在精度丢失问题。

所以这个时候我们就需要使用 px 配合 dpr 来实现:

.circle(@size,@backgroundColor){
  width:@size;
  height:@size;
  background-color:@backgroundColor;
  [data-dpr='1']&{
    width:@size*0.5;
    height:@size*0.5;
  }
  [data-dpr='3']&{
    width:@size*1.5;
    height:@size*1.5;
  }
}

2.1px 细线问题

1.使用伪类 + transform

.border_bottom{
  overflow:hidden;
  position:relative;
  border:none!inportant;
}
.border_bottom:after{
  content:'';
  position:absolute;
  left:0;
  bottom:0;
  width:100%;
  height:1px;
  background-color:#d4d6d7;
  -webkit-transfrom-origin:0 0;
  transfrom-origin:0 0;
  -webkit-transform:scaleY(0.5);
  transform:scaleY(0.5);
}
使用box-shadow模拟
.border_bottom{
  box-shadow:inset 0px -1px 1px -1px #d4d6d7;
}

3. 从 html 元素继承 box-sizing

在大多数情况下我们在设置元素的 borderpadding 并不希望改变元素的 width,height值,这个时候我们就可以为该元素设置 box-sizing:border-box;

我不希望每次都重写一遍,而是希望他是继承而来的,那么我们可以使用如下代码:

html{
  box-sizing:border-box;
}
*,*:before,*:after{
  box-sizing:inherit;
}

这样的好处在于他不会覆盖其他组件的 box-sizing 值,又无需为每一个元素重复设置 box-sizing:border-box;

4. 内联首屏关键 CSS

性能优化中有一个重要的指标 —— 首次有效绘制(FMP),即指页面的首要内容(primary content)出现在屏幕上的时间。这一指标影响用户看到页面前所需等待的时间,而 内联首屏关键 CSS(即 Critical CSS,可以称之为首屏关键 CSS) 能给用户一个更好的心理预期。

我们知道内联 CSS 能够使浏览器开始页面渲染的时间提前,即在 HTML 下载完成之后就能渲染了。

既然是内联关键 CSS,也就说明我们只会将少部分的 CSS 代码直接写入 HTML 中。至于内联哪些 CSS 你可以使用 Critical。

5.超出省略

.line-camp{
  text-overflow:-o-ellipsis-lastline;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-line-clamp:@clamp;
  -webkit-box-orient:vertical;//这句在webpack打包时会省略
}
解决方案
.line-camp{
  text-overflow:-o-ellipsis-lastline;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-line-clamp:@clamp;
  /*!autoprefixer:off*/
  -webkit-box-orient:vertical;//这句在webpack打包时会省略
  /*!autoprefixer:on*/
}

6.两端对齐

html
  <div>姓名</div>
  <div>手机号码</div>
  <div>密码</div>
css
div{
  margin:10px 0;
  width:100px;
  text-align-last:justify;
}

本文摘自公众号 作者:小生方勤「前端词典」系列文章作者,致力于输出对读者有帮助的文章