Fork me on GitHub
余鸢

css小知识总结

简单的文字模糊效果

以下两行简单的CSS3代码可达到将文字模糊化处理的目的,出来的效果有点像使用PS的滤镜。

1
2
3
4
p{
color: transparent;
text-shadow: #111 0 0 5px;
}

效果:

模糊

垂直居中

有好多次博主都有这样的需求,垂直居中显示某个DIV,我们知道CSS中天然有水平居中的样式text-align:center。唯独这个垂直居中无解。

当然你可以将容器设置为display:table,然后将子元素也就是要垂直居中显示的元素设置为display:table-cell,然后加上vertical-align:middle来实现,但此种实现往往会因为display:table而破坏整体布局,那还不如直接用table标签了呢。

下面这个样式利用了translate来巧妙实现了垂直居中样式,需IE9+。

1
2
3
4
5
.center-vertical{
position: relative;
top: 50%;
transform: translateY(-50%);
}

相比而言,水平居中要简单得多,像上面提到的text-align:center,经常用到的技巧还有margin:0 auto。但对于margin大法也只在子元素宽度小于容器宽度时管用,当子元素宽度大于容器宽度时此法失效。

如法炮制,利用lefttransform同样可实现水平居中,不过意义不大,毕竟text-alignmargin差不多满足需求了。

1
2
3
4
5
.center-horizontal{
position: relative;
left: 50%;
transform: translateX(-50%);
}

多重边框

利用重复指定box-shadow来达到多个边框的效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
div {
/* Borders */
box-shadow: 0 0 0 6px rgba(0,0,0,0.2), 0 0 0 12px rgba(0,0,0,0.2), 0 0 0 18px rgba(0,0,0,0.2), 0 0 0 24px rgba(0,0,0,0.2);
/* Meaningless pretty things */
background: linear-gradient(45deg, powderBlue, ghostwhite);
height: 200px;
line-height: 200px;
font-family: sans-serif;
color: MidnightBlue;
margin: 100px auto;
text-align: center;
width: 400px
}
<div>Eh careful man, there's a beverage here eh!</div>

效果:

2

实时编辑CSS

通过设置style标签的display:block样式可以让页面的style标签显示出来,并且加上contentEditable属性后可以让样式成为可编辑状态,更改后的样式效果也是实时更新呈现的。此技巧在IE下无效。拥有此技能者,逆天也!

1
2
3
4
5
6
7
8
<!DOCTYPE html>
<html lang="en">
<body>
<style style="display: block" contenteditable>
body {color:blue}
</style>
</body>
</html>

效果:

0

创建长宽比固定的元素

通过设置父级窗口的padding-bottom可以达到让容器保持一定的长度比的目的,这在响应式页面设计中比较有用,能够保持元素不变形。

1
2
3
4
5
<div style="width: 100%; position: relative; padding-bottom: 20%;">
<div style="position: absolute; left: 0; top: 0; right: 0; bottom: 0; background-color: yellow;">
this content will have a constant aspect ratio that varies based on the width.
</div>
</div>

效果:

2

CSS中也可以做简单运算

通过CSS中的calc方法可以进行一些简单的运算,从而达到动态指定元素样式的目的。

1
2
3
.center{
background-position: calc(100% - 50px) calc(100% - 20px);
}

cursor的一个效果

使用cursor: none!important可以光标消失。

1
2
3
*{
cursor: none!important;
}