CSS揭秘之用户体验

324 阅读2分钟

扩大可点击区域

伪元素可以代表其宿主元素来响应鼠标交互。我们可以在按钮的上层覆盖一层透明的伪元素,并让伪元素在四个方向上都比宿主元素大出 10px

  #myBtn{
      position:relative; 
   }
   #myBtn::before{
        position:absolute;
        content:'';
        top:-10px;
        bottom: -10px;
        right:-10px;
        left:-10px;
   }

自定义复选框

 <input type="checkbox" id="awesome" />
 <label for="awesome">Awesome!</label>
input[type="checkbox"] + label::before {
        content: '\a0'; /* 不换行空格 */
        display: inline-block;
        vertical-align: .2em;
        width: .8em;
        height: .8em;
        margin-right: .2em;
        border-radius: .2em;
        background: silver;
        text-indent: .15em;
        line-height: .65;
    }
input[type="checkbox"]:checked + label::before {
    content: '\2713';
    background: yellowgreen;
}
input[type="checkbox"] {
    position: absolute;
    clip-path: circle(0%);
}
input[type="checkbox"]:focus + label::before {
    box-shadow: 0 0 .1em .1em #58a;
}
input[type="checkbox"]:disabled + label::before {
    background: gray;
    box-shadow: none;
    color: #555;
}    

通过阴影来弱化背景

很多时候,我们需要通过一层半透明的遮罩层来把后面的一切整体调暗,以便凸显某个特定的 UI 元素,引导用户关注。比如,弹出层以及交互式的“快速指南”就是这种效果的典型案例。这个效果最常见的实现方法就是增加一个额外的 HTML 元素用于遮挡背景,然后为它添加如下样式:

 .overlay { /* 用于遮挡背景 */
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background: rgba(0,0,0,.8);
    }
    .lightbox { /* 需要吸引用户注意的元素 */
        position: absolute;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%);
        z-index: 1;
        border:1px solid red;
        width:500px;
        height:400px;
        background:white;
        /* [其余样式] */
    }

交互式的图片对比控件

<div class="image-slider">
    <div>
    <img src="./refresh.png" alt="Before" />
    </div>
    <img src="./refresh_2.png" alt="After" />
</div>
    .image-slider {
        position:relative;
        display: inline-block;
    }
    .image-slider > div {
        position: absolute;
        top: 0; bottom: 0; left: 0;
        width: 50%; /* 初始宽度 */
        overflow: hidden; /* 让它可以裁切图片 */
        resize: horizontal;
    }
    .image-slider > div::before {
        content: '';
        position: absolute;
        bottom: 0; right: 0;
        width: 12px; height: 12px;
        padding: 5px;
        background:
        linear-gradient(-45deg, white 50%, transparent 0);
        background-clip: content-box;
        cursor: ew-resize;
    }
    .image-slider img { display: block; }