CSS那些超好用的样式

123 阅读2分钟

1、选择第n个标签

<div class="content">
    <span class="one"></span>
    <span class="two"></span>
    <span class="three"></span>
</div>

选择content下第 1 个标签

.content {
    span:first-child {
        color: red;
    }
}

选择content下最后 1 个标签

.content {
    span:last-child {
        color: red;
    }
}

选择content下第n个标签

.content {
    span:nth-child(n) {
        color: red;
    }
}

选择content下第 2 位开始到结尾的标签

.content {
    span:nth-child(n+2) {
        color: red;
    }
}

选择content下前 3 个标签

.content {
    span:nth-child(-n+3) {
        color: red;
    }
}

2、、border、padding不计入宽高

box-sizing: border-box;
-moz-box-sizing: border-box; /* Firefox */ 
-webkit-box-sizing: border-box; /* Safari */

3、把图片设置为背景

background: url("~@/assets/images/login/bg.png") center center no-repeat;
background-size: 100% 100%;

4、伪类样式

以tab栏下划线举例

content: "";
width: 60%;
height: 0.04rem;
background-color: $blue;
position: absolute;
bottom: -6px;
left: 50%;
transform: translate(-50%, 0);

常用伪类

  1. :hover 鼠标悬浮
  2. :active 鼠标按下不松开
  3. :before
  4. :after

5、文字溢出省略号

overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; // 几行省略
-webkit-box-orient: vertical;

6、纯字母换行

word-break: break-all; // 只对英文起作用,以字母作为换行依据
word-wrap: break-word; // 只对英文起作用,以单词作为换行依据

7、三角形、梯形

三角形: 元素本身没有画三角形的样式,但是边框两边是斜角,所以只要把元素宽高设为0,再把边框设成透明,保留其中一个边框即可

width: 0;
height: 0;
border-bottom: 100px solid #333;
border-left: 100px solid transparent;
border-right: 100px solid transparent;

梯形: 和三角形原理相同,但是需要设置宽度或者高度其中之一,边框依然只保留其中一个颜色,其余皆设置为透明,但两边要比保留的那一边要小

width: 100px;
height: 0;
border-bottom: 100px solid #333;
border-left: 30px solid transparent;
border-right: 30px solid transparent;

8、事件穿透

pointer-events: none; // 捕获不到任何点击,让事件穿透到它的下面,默认auto

9、文字水平对齐

text-align: right;
text-align: left; 
text-align: center; 

10、绝对定位

举例: 垂直水平居中

// 父元素
position: relative;

// 子元素
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);