前端奇奇怪怪的CSS样式

图形裁剪

            /* 圆  半径大小 at 圆心的坐标位置(X Y) */
            clip-path: circle(50% at 50% 50%);
            /* 椭圆 半径大小(X Y) at 圆心的坐标位置(X Y)*/
            clip-path: ellipse(25% 40% at 50% 50%);
            /* 矩形 外边距 */
            clip-path: inset(5% 20% 15% 10%);
            /* 多边形 各个顶点的坐标位置*/
            clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
            clip-path: path('M 100 100 L 400 100 L 400 200 L 275 200 L 275 500 L 225 500 L 225 200 L 100 200 z');

 

边框文字

    <fieldset>
        一
        <legend>二</legend>
    </fieldset>

 

多背景图片拼贴

            background-image: url(), url();
            background-position: left top,right bottom;
            background-repeat: repeat,no-repeat;

特殊符号

<!-- 大于号 & g t;小于号& l t;双引号& q u o t;版权& c o p y; -->

 

水平居中

margin: 0 auto;

 垂直居中

vertical-align: middle;

 文本居中

text-align: center;

 

水平居中和垂直居中(对子元素)

    display: flex;
    /* 主轴水平居中 */
    align-items: center;
    /* 主轴垂直居中 */
    justify-content: center;

 

    display: table-cell;
    text-align: center;
    vertical-align: middle;

 

水平排列

display: inline-block;

使用inline-block相当于将元素介于块级元素与行内元素之间,将换行符转换成了空格,因此各个元素之间会有空隙

flaot:left;

 各个元素没有间隙,且元素自身大小不会改变,若一行容不下,则会换行

水平排列(对子元素)

    display: flex;
    /* 沿垂直主轴上下水平排列 */
    flex-direction: row;

 一定会将定义了该属性的元素同一行,哪怕改变元素自身大小

圆角

border-radius: 15px;

 

重叠元素

position:absolute;
z-index:5;

 z-index只在position为relative或者absolute或者fixed时生效

阴影

box-shadow: 0 20px 20px 0 rgba(8, 182, 212, 0.822);

 

filter: drop-shadow(20px 20px 10px #000); 

 

 元素移动

transform: translate(10px,20px);//X+10px,Y+20px

 

position: relative;
left: 10px;
top: 20px;

 这两种方法的区别在与%,translate的百分比大小是相对自身的大小,而使用relative的百分比则是相对父元素的大小

元素旋转

transform: rotate(180deg);

 

元素倾斜

transform: skew(3deg,30deg);

 

边框样式和颜色

border-style:dotted solid double dashed; 
border-color:#000;

 样式:点状,实线,双线,虚线

动画

        img {
            animation: name 3s linear infinite;
            animation-play-state: running;
        }

        @keyframes name {
            from {
                background-color:red;
            }

            to {
                background-color:blue);
            }
        }

name是自定义的动画名称,后面可以跟动画持续时间,linear是匀速变化,infinite是重复播放动画

animation-play-state定义动画的状态可以是runnig或者paused

继承

width: inherit;

 inherit可以继承父元素的属性

图片保持原有比例剪切

object-fit: cover;

 

图片保持原有比例缩放

object-fit: contain;

 

透明度

opacity:0.5;

 作用于元素,字体等也会变得透明

background-color:rgba(255,0,0,0.5);

作用于背景 ,只有背景会变得透明,rgba为红绿蓝透明度

过渡延迟

div
{
	width:100px;
	height:100px;
	background:red;
	transition:width 2s;
	
}

div:hover
{
	width:300px;
}

 

取消下划线

text-decoration: none;

 

取消列表样式

list-style: none;

 

媒体查询

@media screen and (max-width: 300px) {
    body {
        background-color:lightblue;
    }
}

 查看浏览器大小,当浏览器屏幕小于300px时改变颜色

        @media (prefers-color-scheme:light) {
            .father{
                background-color: #fff;
                color: #000;
            }
        }
        @media (prefers-color-scheme:dark) {
            .father{
                background-color: #000;
                color: #fff;
            }
        }

 根据浏览器默认主题改变颜色

计算元素的宽度

width: calc(100% - 100px);

 

渐变色

background-image: linear-gradient(to left, red, yellow, blue);

 

background-image: linear-gradient(30deg, red, yellow, blue);

 径向渐变使用radial-gradient()

background: radial-gradient(circle at 50% 50%, transparent 10px,yellow 50%,transparent 100px);

 锥形渐变

background: conic-gradient(from 45deg, white, black, white);

 

突变色

background-image: linear-gradient(to right, #ffbdbd 0%, #ffbdbd 50%, #c3ede5 50%, #c3ede5 100%);

 

改变选中文本的字体颜色

        .content::selection{
            background-color: #ff9900;
            color: #fff;
        }

 

首字放大

        .content::first-letter{
            font-size: 48px;
        }

 

黑白滤镜

        .content{
            background-image: url(img/离人.jpg);
            background-size: contain;
            filter: grayscale(100%);
        }

 

模糊滤镜

filter: blur(5px);

 对该元素进行模糊

backdrop-filter: blur(5px); 

 对该元素背后的元素进行模糊

高度自适应

.container {
    display: flex;
    min-height: 100vh;//vh为视窗高度的百分比,1vh代表视窗高度为1%
    flex-direction:column;
}
content {
    background: #bbbbbb;
    flex: 1;
    /* 1 代表盡可能最大,會自動填滿除了 header footer 以外的空間 */
}

 

自定义颜色

        :root{
            --bgColor:#66e6fe;
        }
        .container {
            background: var(--bgColor);
        }

 

悬浮窗

.box{
            width: 100px;
            height: 10vh;
            top: 100px;
            position: fixed;
            background-color: #fff;
        }

 

文字阴影与文字轮廓

            text-shadow: 0px 0px #000; 
            -webkit-text-stroke: 0.3px #000;

 

让弹性盒元素在必要的时候拆行

display:flex;
flex-wrap: wrap;

 

添加伪元素

        .header .title .box::before {
            content: "";
            background-color: #ff4b1f;
            width: 15px;
            height: 15px;
            position: relative;
            top: 3px;
            left: -7px;
            display:inline-block;
        }

 使用伪类

        /* 奇数行居中 */
        .container .side tr:nth-of-type(odd){
            text-align: center;
        }
        /* 偶数行 控制行距*/
        .container .side tr:nth-of-type(even) td{
            padding-top: 35px;
        }        

 

取消鼠标事件

pointer-events: none;

 

动感卡片

<script type="text/javascript" src="./vanilla-tilt.js"></script>
<script>
    VanillaTilt.init(document.querySelectorAll(".card"),{
        max:25,
        speed:400
    });
</script>

 引入vanilla-tilt.js

var VanillaTilt = (function () {
'use strict';

/**
 * Created by Sergiu Șandor (micku7zu) on 1/27/2017.
 * Original idea: https://github.com/gijsroge/tilt.js
 * MIT License.
 * Version 1.7.2
 */

class VanillaTilt {
  constructor(element, settings = {}) {
    if (!(element instanceof Node)) {
      throw ("Can't initialize VanillaTilt because " + element + " is not a Node.");
    }

    this.width = null;
    this.height = null;
    this.clientWidth = null;
    this.clientHeight = null;
    this.left = null;
    this.top = null;

    // for Gyroscope sampling
    this.gammazero = null;
    this.betazero = null;
    this.lastgammazero = null;
    this.lastbetazero = null;

    this.transitionTimeout = null;
    this.updateCall = null;
    this.event = null;

    this.updateBind = this.update.bind(this);
    this.resetBind = this.reset.bind(this);

    this.element = element;
    this.settings = this.extendSettings(settings);

    this.reverse = this.settings.reverse ? -1 : 1;
    this.glare = VanillaTilt.isSettingTrue(this.settings.glare);
    this.glarePrerender = VanillaTilt.isSettingTrue(this.settings["glare-prerender"]);
    this.fullPageListening = VanillaTilt.isSettingTrue(this.settings["full-page-listening"]);
    this.gyroscope = VanillaTilt.isSettingTrue(this.settings.gyroscope);
    this.gyroscopeSamples = this.settings.gyroscopeSamples;

    this.elementListener = this.getElementListener();

    if (this.glare) {
      this.prepareGlare();
    }

    if (this.fullPageListening) {
      this.updateClientSize();
    }

    this.addEventListeners();
    this.reset();
    this.updateInitialPosition();
  }

  static isSettingTrue(setting) {
    return setting === "" || setting === true || setting === 1;
  }

  /**
   * Method returns element what will be listen mouse events
   * @return {Node}
   */
  getElementListener() {
    if (this.fullPageListening) {
      return window.document;
    }

    if (typeof this.settings["mouse-event-element"] === "string") {
      const mouseEventElement = document.querySelector(this.settings["mouse-event-element"]);

      if (mouseEventElement) {
        return mouseEventElement;
      }
    }

    if (this.settings["mouse-event-element"] instanceof Node) {
      return this.settings["mouse-event-element"];
    }

    return this.element;
  }

  /**
   * Method set listen methods for this.elementListener
   * @return {Node}
   */
  addEventListeners() {
    this.onMouseEnterBind = this.onMouseEnter.bind(this);
    this.onMouseMoveBind = this.onMouseMove.bind(this);
    this.onMouseLeaveBind = this.onMouseLeave.bind(this);
    this.onWindowResizeBind = this.onWindowResize.bind(this);
    this.onDeviceOrientationBind = this.onDeviceOrientation.bind(this);

    this.elementListener.addEventListener("mouseenter", this.onMouseEnterBind);
    this.elementListener.addEventListener("mouseleave", this.onMouseLeaveBind);
    this.elementListener.addEventListener("mousemove", this.onMouseMoveBind);

    if (this.glare || this.fullPageListening) {
      window.addEventListener("resize", this.onWindowResizeBind);
    }

    if (this.gyroscope) {
      window.addEventListener("deviceorientation", this.onDeviceOrientationBind);
    }
  }

  /**
   * Method remove event listeners from current this.elementListener
   */
  removeEventListeners() {
    this.elementListener.removeEventListener("mouseenter", this.onMouseEnterBind);
    this.elementListener.removeEventListener("mouseleave", this.onMouseLeaveBind);
    this.elementListener.removeEventListener("mousemove", this.onMouseMoveBind);

    if (this.gyroscope) {
      window.removeEventListener("deviceorientation", this.onDeviceOrientationBind);
    }

    if (this.glare || this.fullPageListening) {
      window.removeEventListener("resize", this.onWindowResizeBind);
    }
  }

  destroy() {
    clearTimeout(this.transitionTimeout);
    if (this.updateCall !== null) {
      cancelAnimationFrame(this.updateCall);
    }

    this.reset();

    this.removeEventListeners();
    this.element.vanillaTilt = null;
    delete this.element.vanillaTilt;

    this.element = null;
  }

  onDeviceOrientation(event) {
    if (event.gamma === null || event.beta === null) {
      return;
    }

    this.updateElementPosition();

    if (this.gyroscopeSamples > 0) {
      this.lastgammazero = this.gammazero;
      this.lastbetazero = this.betazero;

      if (this.gammazero === null) {
        this.gammazero = event.gamma;
        this.betazero = event.beta;
      } else {
        this.gammazero = (event.gamma + this.lastgammazero) / 2;
        this.betazero = (event.beta + this.lastbetazero) / 2;
      }

      this.gyroscopeSamples -= 1;
    }

    const totalAngleX = this.settings.gyroscopeMaxAngleX - this.settings.gyroscopeMinAngleX;
    const totalAngleY = this.settings.gyroscopeMaxAngleY - this.settings.gyroscopeMinAngleY;

    const degreesPerPixelX = totalAngleX / this.width;
    const degreesPerPixelY = totalAngleY / this.height;

    const angleX = event.gamma - (this.settings.gyroscopeMinAngleX + this.gammazero);
    const angleY = event.beta - (this.settings.gyroscopeMinAngleY + this.betazero);

    const posX = angleX / degreesPerPixelX;
    const posY = angleY / degreesPerPixelY;

    if (this.updateCall !== null) {
      cancelAnimationFrame(this.updateCall);
    }

    this.event = {
      clientX: posX + this.left,
      clientY: posY + this.top,
    };

    this.updateCall = requestAnimationFrame(this.updateBind);
  }

  onMouseEnter() {
    this.updateElementPosition();
    this.element.style.willChange = "transform";
    this.setTransition();
  }

  onMouseMove(event) {
    if (this.updateCall !== null) {
      cancelAnimationFrame(this.updateCall);
    }

    this.event = event;
    this.updateCall = requestAnimationFrame(this.updateBind);
  }

  onMouseLeave() {
    this.setTransition();

    if (this.settings.reset) {
      requestAnimationFrame(this.resetBind);
    }
  }

  reset() {
    this.event = {
      clientX: this.left + this.width / 2,
      clientY: this.top + this.height / 2
    };

    if (this.element && this.element.style) {
      this.element.style.transform = `perspective(${this.settings.perspective}px) ` +
        `rotateX(0deg) ` +
        `rotateY(0deg) ` +
        `scale3d(1, 1, 1)`;
    }

    this.resetGlare();
  }

  resetGlare() {
    if (this.glare) {
      this.glareElement.style.transform = "rotate(180deg) translate(-50%, -50%)";
      this.glareElement.style.opacity = "0";
    }
  }

  updateInitialPosition() {
    if (this.settings.startX === 0 && this.settings.startY === 0) {
      return;
    }

    this.onMouseEnter();

    if (this.fullPageListening) {
      this.event = {
        clientX: (this.settings.startX + this.settings.max) / (2 * this.settings.max) * this.clientWidth,
        clientY: (this.settings.startY + this.settings.max) / (2 * this.settings.max) * this.clientHeight
      };
    } else {
      this.event = {
        clientX: this.left + ((this.settings.startX + this.settings.max) / (2 * this.settings.max) * this.width),
        clientY: this.top + ((this.settings.startY + this.settings.max) / (2 * this.settings.max) * this.height)
      };
    }


    let backupScale = this.settings.scale;
    this.settings.scale = 1;
    this.update();
    this.settings.scale = backupScale;
    this.resetGlare();
  }

  getValues() {
    let x, y;

    if (this.fullPageListening) {
      x = this.event.clientX / this.clientWidth;
      y = this.event.clientY / this.clientHeight;
    } else {
      x = (this.event.clientX - this.left) / this.width;
      y = (this.event.clientY - this.top) / this.height;
    }

    x = Math.min(Math.max(x, 0), 1);
    y = Math.min(Math.max(y, 0), 1);

    let tiltX = (this.reverse * (this.settings.max - x * this.settings.max * 2)).toFixed(2);
    let tiltY = (this.reverse * (y * this.settings.max * 2 - this.settings.max)).toFixed(2);
    let angle = Math.atan2(this.event.clientX - (this.left + this.width / 2), -(this.event.clientY - (this.top + this.height / 2))) * (180 / Math.PI);

    return {
      tiltX: tiltX,
      tiltY: tiltY,
      percentageX: x * 100,
      percentageY: y * 100,
      angle: angle
    };
  }

  updateElementPosition() {
    let rect = this.element.getBoundingClientRect();

    this.width = this.element.offsetWidth;
    this.height = this.element.offsetHeight;
    this.left = rect.left;
    this.top = rect.top;
  }

  update() {
    let values = this.getValues();

    this.element.style.transform = "perspective(" + this.settings.perspective + "px) " +
      "rotateX(" + (this.settings.axis === "x" ? 0 : values.tiltY) + "deg) " +
      "rotateY(" + (this.settings.axis === "y" ? 0 : values.tiltX) + "deg) " +
      "scale3d(" + this.settings.scale + ", " + this.settings.scale + ", " + this.settings.scale + ")";

    if (this.glare) {
      this.glareElement.style.transform = `rotate(${values.angle}deg) translate(-50%, -50%)`;
      this.glareElement.style.opacity = `${values.percentageY * this.settings["max-glare"] / 100}`;
    }

    this.element.dispatchEvent(new CustomEvent("tiltChange", {
      "detail": values
    }));

    this.updateCall = null;
  }

  /**
   * Appends the glare element (if glarePrerender equals false)
   * and sets the default style
   */
  prepareGlare() {
    // If option pre-render is enabled we assume all html/css is present for an optimal glare effect.
    if (!this.glarePrerender) {
      // Create glare element
      const jsTiltGlare = document.createElement("div");
      jsTiltGlare.classList.add("js-tilt-glare");

      const jsTiltGlareInner = document.createElement("div");
      jsTiltGlareInner.classList.add("js-tilt-glare-inner");

      jsTiltGlare.appendChild(jsTiltGlareInner);
      this.element.appendChild(jsTiltGlare);
    }

    this.glareElementWrapper = this.element.querySelector(".js-tilt-glare");
    this.glareElement = this.element.querySelector(".js-tilt-glare-inner");

    if (this.glarePrerender) {
      return;
    }

    Object.assign(this.glareElementWrapper.style, {
      "position": "absolute",
      "top": "0",
      "left": "0",
      "width": "100%",
      "height": "100%",
      "overflow": "hidden",
      "pointer-events": "none"
    });

    Object.assign(this.glareElement.style, {
      "position": "absolute",
      "top": "50%",
      "left": "50%",
      "pointer-events": "none",
      "background-image": `linear-gradient(0deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%)`,
      "transform": "rotate(180deg) translate(-50%, -50%)",
      "transform-origin": "0% 0%",
      "opacity": "0",
    });

    this.updateGlareSize();
  }

  updateGlareSize() {
    if (this.glare) {
      const glareSize = (this.element.offsetWidth > this.element.offsetHeight ? this.element.offsetWidth : this.element.offsetHeight) * 2;

      Object.assign(this.glareElement.style, {
        "width": `${glareSize}px`,
        "height": `${glareSize}px`,
      });
    }
  }

  updateClientSize() {
    this.clientWidth = window.innerWidth
      || document.documentElement.clientWidth
      || document.body.clientWidth;

    this.clientHeight = window.innerHeight
      || document.documentElement.clientHeight
      || document.body.clientHeight;
  }

  onWindowResize() {
    this.updateGlareSize();
    this.updateClientSize();
  }

  setTransition() {
    clearTimeout(this.transitionTimeout);
    this.element.style.transition = this.settings.speed + "ms " + this.settings.easing;
    if (this.glare) this.glareElement.style.transition = `opacity ${this.settings.speed}ms ${this.settings.easing}`;

    this.transitionTimeout = setTimeout(() => {
      this.element.style.transition = "";
      if (this.glare) {
        this.glareElement.style.transition = "";
      }
    }, this.settings.speed);

  }

  /**
   * Method return patched settings of instance
   * @param {boolean} settings.reverse - reverse the tilt direction
   * @param {number} settings.max - max tilt rotation (degrees)
   * @param {startX} settings.startX - the starting tilt on the X axis, in degrees. Default: 0
   * @param {startY} settings.startY - the starting tilt on the Y axis, in degrees. Default: 0
   * @param {number} settings.perspective - Transform perspective, the lower the more extreme the tilt gets
   * @param {string} settings.easing - Easing on enter/exit
   * @param {number} settings.scale - 2 = 200%, 1.5 = 150%, etc..
   * @param {number} settings.speed - Speed of the enter/exit transition
   * @param {boolean} settings.transition - Set a transition on enter/exit
   * @param {string|null} settings.axis - What axis should be disabled. Can be X or Y
   * @param {boolean} settings.glare - What axis should be disabled. Can be X or Y
   * @param {number} settings.max-glare - the maximum "glare" opacity (1 = 100%, 0.5 = 50%)
   * @param {boolean} settings.glare-prerender - false = VanillaTilt creates the glare elements for you, otherwise
   * @param {boolean} settings.full-page-listening - If true, parallax effect will listen to mouse move events on the whole document, not only the selected element
   * @param {string|object} settings.mouse-event-element - String selector or link to HTML-element what will be listen mouse events
   * @param {boolean} settings.reset - false = If the tilt effect has to be reset on exit
   * @param {gyroscope} settings.gyroscope - Enable tilting by deviceorientation events
   * @param {gyroscopeSensitivity} settings.gyroscopeSensitivity - Between 0 and 1 - The angle at which max tilt position is reached. 1 = 90deg, 0.5 = 45deg, etc..
   * @param {gyroscopeSamples} settings.gyroscopeSamples - How many gyroscope moves to decide the starting position.
   */
  extendSettings(settings) {
    let defaultSettings = {
      reverse: false,
      max: 15,
      startX: 0,
      startY: 0,
      perspective: 1000,
      easing: "cubic-bezier(.03,.98,.52,.99)",
      scale: 1,
      speed: 300,
      transition: true,
      axis: null,
      glare: false,
      "max-glare": 1,
      "glare-prerender": false,
      "full-page-listening": false,
      "mouse-event-element": null,
      reset: true,
      gyroscope: true,
      gyroscopeMinAngleX: -45,
      gyroscopeMaxAngleX: 45,
      gyroscopeMinAngleY: -45,
      gyroscopeMaxAngleY: 45,
      gyroscopeSamples: 10
    };

    let newSettings = {};
    for (var property in defaultSettings) {
      if (property in settings) {
        newSettings[property] = settings[property];
      } else if (this.element.hasAttribute("data-tilt-" + property)) {
        let attribute = this.element.getAttribute("data-tilt-" + property);
        try {
          newSettings[property] = JSON.parse(attribute);
        } catch (e) {
          newSettings[property] = attribute;
        }

      } else {
        newSettings[property] = defaultSettings[property];
      }
    }

    return newSettings;
  }

  static init(elements, settings) {
    if (elements instanceof Node) {
      elements = [elements];
    }

    if (elements instanceof NodeList) {
      elements = [].slice.call(elements);
    }

    if (!(elements instanceof Array)) {
      return;
    }

    elements.forEach((element) => {
      if (!("vanillaTilt" in element)) {
        element.vanillaTilt = new VanillaTilt(element, settings);
      }
    });
  }
}

if (typeof document !== "undefined") {
  /* expose the class to window */
  window.VanillaTilt = VanillaTilt;

  /**
   * Auto load
   */
  VanillaTilt.init(document.querySelectorAll("[data-tilt]"));
}

return VanillaTilt;

}());

 

posted @ 2022-07-14 19:48  霖霖的信箱  阅读(104)  评论(0)    收藏  举报