可能用到的Css小技巧

514 阅读2分钟

页面锚点跳转平滑过渡

  • 再也不用因为一个简单的页面间跳转写一大堆js处理滚动条了
<style>
html{
  scroll-behavior: smooth;
}
</style>
<div id="id2">
    <a href="#id1">go id1</a>
</div>
<div style="height: 3000px;"></div>
<div id="id1">
    <a href="#id2">go id2</a>
</div>

2021-07-15 17.52.53.gif

css实现单页滚动的简易方案

首先直接上代码

<style>
    .wrapper{
      height: 100vh;
      overflow: auto;
      scroll-snap-type: y mandatory;
    }
    .section{
      height: 100vh;
      scroll-snap-align: center;
      font-size: 30px;
      text-align: center;
      line-height: 100vh;
    }
</style>

<div class="wrapper">
    <div class="section">1</div>
    <div class="section">2</div>
    <div class="section">3</div>
    <div class="section">4</div>
    <div class="section">5</div>
</div>

关键代码-scroll-snap-type

  • scroll-snap-type属性定义在滚动容器中的一个临时点(snap point)如何被严格的执行。
  • scroll-snap-type 附带两个参数,第一个代表捕捉到方向,第二个代表模式[mandatory | proximity],mandatory表示强制将滚动结束后元素的停留位置设置到我们规定的地方。
  • 在子元素中,使用scroll-snap-align,来标记定位到方位,有[start | center | end]三个值可选
  • 一般来说,给子容器和父容器设置相同的高度,即可简易的实现整页滚动的效果,适用于大部分主流浏览器

2021-07-16 12.00.00.gif

给png图片增加阴影

使用滤镜filter: drop-shadow(2px 4px 8px #585858);

<style>
    img{
      display: block;
      width: 300px;
    }
    .shadow{
      filter: drop-shadow(2px 4px 8px #0f0);
    }
</style>

  <img src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png">
  <img class="shadow" src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png">

效果如下: image.png

打字效果

  • ch等于一个0的宽度,一般来说,是相对于当前字体大小的计量单位
    • 前提需要设置等宽字体,不然可能会计量不准确
    • 适合全是中文或者全是英文的地方
    • 1ch = 1个英文 = 1个数字
    • 2ch = 1个中文
  <style>
    .text{
      font-family: Consolas, Monaco, monospace;
      width: 10ch;
      overflow: hidden;
      animation: typing 2s steps(10), blink .5s step-end infinite alternate;
      border-right: 2px solid;
      white-space: nowrap;
    }
    @keyframes typing {
      0% {
        width: 0;
      }
    }
    @keyframes blink {
      50%{
        border-color: transparent;
      }
    }
  </style>
  <div class="text">0000000000</div>

2021-07-15 17.44.08.gif

粘性标题

效果可以直接参照 菜鸟教程

需要注意的是,父元素的高度不能低于sticky元素的高度, 例如下方代码,当.w的高度低于1020px时,就会无效

  <style>
    .w{
      height: 1500px;
    }
    .p{
      position: sticky; 
      top: 20px;
    }
    .h{
      background-color: #cecece;
      height: 1000px;
    }
  </style>
  
  <div class="w">
    <div class="h"></div>
    <div class="p">标题</div>
    <div class="h"></div>
  </div>

美化控制台打印

使用console.log的时候添加css样式

  • 在第一个内容中加上 %c即可为其添加css样式
  • 一个%c对应一个样式,只有第一个里面参数里的%c才有效
  • 支持的语法,效果如下:
console.log('%c red %c green','color: red','color: green')
console.log('%c red %c green %c none','color: red','color: green')
console.log('%c red %c green','color: red', 'color: green', 'color: blue')

image.png

浏览器兼容查询