css 实用小技巧

239 阅读1分钟

position + margin 实现的自适应

  • 自适应垂直水平居中
        .box {
            width: 400px;
            height: 400px;
            background: #00aeef;
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }
  • 自适元素应宽度 例如标题下划线

    <div class="title">
        短标题 / 长标题
    </div>

    <style>
        .title {
            display: inline-block;
            position: relative;
            font-size: 24px;
        }
        .title::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            bottom: -14px;
            margin: 0 10px;
            height: 8px;
            background: #00aeef;
            border-radius: 10px;
        }
    </style>

全屏水印

  • 给水印层添加 pointer-events: none 就不会遮挡页面正常操作事件了;
    <div class="mask"></div>
    <div class="content"></div>
    <style>
        .mask {
            width: 100%;
            height: 100%;
            background: url(...);
            position: fixed;
            left: 0;
            top: 0;
            z-index: 100;
            pointer-events: none;
        }
    </style>

丝滑滚动

    <style>
        .box{
            scroll-behavior: smooth;
        }
    </style>

animation 逐帧动画

    <div class="ani"></div>
    <style>
        .ani {
            width: 280px;
            height: 280px;
            background: url(...) 0 0 no-repeat;
            background-size: auto 100%;
            margin: 0 auto;
            animation: ani 1.2s linear infinite;
            animation-timing-function: steps(帧数, end);
        }

        @keyframes ani {
            0% {
                background-position: 0 0;
            }

            100% {
                background-position: -(帧数*宽度) 0;
            }
        }
    </style>

多行文本溢出省略

    <style>
        .text {
            display: -webkit-box;
            word-break: break-all;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: //行数;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>

背景图片铺满

  • 使用background-size 的 cover 属性; 可以实现背景图片的自适应铺满 自动检测宽高等比放大图片; 使图片铺满容器;
    <style>
        .box {
            background: url(...) center no-repeat;
            background-size: cover
        }
    </style>

使用css3绘制优惠券

  • 先用渐变属性绘制透明点; 然后设置background-size; 渐变背景会根据设置的背景尺寸来repeat; 然后通过background-position 来控制透明点的展示位置 最终就实现了优惠券的外轮廓;
    <div class="box"></div>

    <style>
        .box {
            width: 300px;
            height: 150px;
            background: radial-gradient(circle at 20px 20px, transparent 0, transparent 20px, #00aeef 21px);
            background-position: 80px -20px;
            background-size: 100% 100%;
            border-radius: 20px;
        }
    </style>

image.png

  • 待续...