css小技巧(二)

82 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情

一些小技巧可以让我们的开发更加高效,事半功倍,我们一起看看吧~

box-sizing

盒子模型是指:外边距(margin)+ border(边框) + 内边距(padding)+ content(内容)

设置box-sizing:border-box属性之后,padding和border的值就不会在影响元素的宽高,这时我们设置的元素的宽高就是真实的盒子的宽高。

为了避免繁琐,每个元素都要设置box-sizing,可以给根节点设置box-sizing,子元素继承它。

子元素box-sizing继承html

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

image.png

表格单元格等宽

  • 给table添加table-layout: fixed 来保持单元格的等宽
  • 给td添加 word-break: break-all
table {  
    table-layout: fixed;
}

用Flexbox布局

通过使用flexbox的 space-between 属性,就可以不需要用nth-,first-,和 last-child 了,列表分隔符就会在均匀间隔的位置出现。

.list {
    display: flex;
    justify-content: space-between;
}
.list .column {
    flex-basis: 23%;
    border: 1px solid #cccccc;
}
.list .column::after {
    content: "我是结束标志";
    color: red;
}

image.png

使用属性选择器用于空链接

当a元素没有文本值,但 href 属性有链接的时候显示链接

a[href^="http"]:empty::before {  
    content: attr(href);
}

CSS绘制三角形

  • 上箭头:设置底部边框,左右设置透明边框
.arrow-up {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-bottom: 5px solid #2f2f2f;
    font-size: 0;
    line-height: 0;
}

  • 下箭头:设置顶部边框,左右设置透明边框
.arrow-down {
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #2f2f2f;
    font-size: 0;
    line-height: 0;
}
  • 左箭头:设置右边边框,上下设置透明边框
.arrow-left {
    width: 0;
    height: 0;
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    border-right: 5px solid #2f2f2f;
    font-size: 0;
    line-height: 0;
}
  • 右箭头:设置左边边框,上下设置透明边框
.arrow-right {
    width: 0;
    height: 0;
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    border-left: 5px solid #2f2f2f;
    font-size: 0;
    line-height: 0;
}

calc()

calc() 用法类似于函数,能够给元素设置动态的值,可以使用简单的运算符

.simpleBlock {
    width: calc(100% - 100px);
}
.complexBlock {
    width: calc(100% - 50% / 3);
    padding: 5px calc(3% - 2px);
    margin-left: calc(10% + 10px);
}

文本渐变

文本渐变效果很流行,设置背景色渐变

.title{
    font-size: 48px;
    font-weight: bold;
    color: #FFFFFF;
    background: linear-gradient(180deg,#FFFFFF 0%, #9DF5FF 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

禁用鼠标事件

使用属性pointer-events ,可以禁用元素的鼠标事件,该元素就无法点击

.disabled { 
    pointer-events: none; 
}

模糊文本

使用css代码就可以实现文本模糊效果

.blur {  
    color: transparent;   
    text-shadow: 0 0 5px rgba(0,0,0,0.5);
}

image.png