CSS实用技巧,前端必备!
2024-01-29 22:00:44
作为前端,在工作中难免会遇到关于排版的问题,以下是我整理的一些关于CSS的技巧,希望对你能有帮助。
1、每个单词的首字母大写
一般我们会用JS实现,其实CSS就可以实现。
```
text-transform: capitalize;
```
2、**元素选中**
使用CSS伪类可以让我们做到这个效果,只需几行简单的代码:
```
::-moz-selection {
background: #b3d4fc;
color: #000;
}
::selection {
background: #b3d4fc;
color: #000;
}
```
3、超链接禁用样式
a[href="#"] { pointer-events: none; cursor: default; }
4、垂直居中
使用绝对定位和负边距可以实现垂直居中。
```
.container {
position: relative;
}
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
5、使用CSS创建边框阴影
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
6、CSS绘制三角形
.triangle { width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 100px solid #f00; }
7、多列布局
使用CSS的column-count属性可以创建多列布局。
.container { column-count: 3; }
8、伪元素创建三角形
```
.triangle {
position: relative;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 20px solid red;
}
.triangle::before {
content: "";
position: absolute;
top: -20px;
left: -10px;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 20px solid red;
}
```
9、行内块元素水平居中
```
.container {
display: flex;
justify-content: center;
align-items: center;
}
.item {
display: inline-block;
}
```
10、文字垂直居中
.container { display: flex; justify-content: center; align-items: center; text-align: center; }
11、文本溢出省略号
.container { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; }
12、图像裁剪为圆形
.image { border-radius: 50%; }
13、给文本添加下划线
text-decoration: underline;
14、给文本添加删除线
text-decoration: line-through;
15、文本大小写转换
text-transform: uppercase;