:before和:after的一些惊人用法
文章目录
清除浮动 clearfix hack
如果父元素容器里面的子元素是浮动元素的话,我们一般需要在父元素闭合前添加一个clear:both的元素用于清除浮动从而能使父容器正常被子元素内容撑起,但是这种方法引入了多余的无意义标签,并且有javascript操作子元素的时候容易引发bug。一种更好的方法是利用CSS,所以在一些CSS文件中经常会看到类似于.clearfix这样的类出没,只要在父容器上应用这个类即可实现清除浮动。下面是利用:before和:after的一个实现:(via Nicolas Gallagher)
1 2 |
.clear-fix { *overflow: hidden; *zoom: 1; }
.clear-fix:after { display: table; content: ""; width: 0; clear: both; } |
段落头部的大引号
许多人喜欢给 blockquote 引用段添加巨大的引号作为背景,这种时候我们就可以用 :before 来代替 background 了,即可以给背景留下空间,还可以直接使用文字而非图片:
1 2 3 4 5 6 7 8 9 |
blockquote::before {
content: open-quote;
position: absolute;
z-index: -1;
color: #DDD;
font-size: 120px;
font-family: serif;
font-weight: bolder;
} |
CSS实现的八卦图案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#yin-yang {
width: 96px;
height: 48px;
background: #eee;
border-color: red;
border-style: solid;
border-width: 2px 2px 50px 2px;
border-radius: 100%;
position: relative;
}
#yin-yang:before {
content: "";
position: absolute;
top: 50%;
left: 0;
background: #eee;
border: 18px solid red;
border-radius: 100%;
width: 12px;
height: 12px;
}
#yin-yang:after {
content: "";
position: absolute;
top: 50%;
left: 50%;
background: red;
border: 18px solid #eee;
border-radius:100%;
width: 12px;
height: 12px;
} |
特效妙用
除了简单的添加字符,配合 CSS 强大的定位和特效特性,完全可以达到给简单的元素另外附加最多两个容器的效果。有一点需要注意的是,如果不需要内容仅配合样式属性做出效果,内容属性也不能为空,即 content:”” 。否则,其他的样式属性一概不会生效。 鼠标移上链接,出现方括号:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
a {
position: relative;
display: inline-block;
outline: none;
text-decoration: none;
color: #000;
font-size: 32px;
padding: 5px 10px;
}
a:hover::before, a:hover::after { position: absolute; }
a:hover::before { content: "\5B"; left: -20px; }
a:hover::after { content: "\5D"; right: -20px; } |
同样,我们只需要配合 display: block 和 position: absolute ,就可以将其当成两个容器,拼合成悬浮出现双边框的特效:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
a {
position: relative;
display: inline-block;
outline: none;
text-decoration: none;
color: #000;
font-size: 32px;
padding: 0 10px;
}
/* 大框 */
a:hover::before, a:hover::after {
content: "";
display: block;
position: absolute;
top: -15%%;
left: -14%%;
width: 120%;
height: 120%;
border-style: solid;
border-width: 4px;
border-color: #DDD;
}
/* 小框 */
a:hover::after {
top: 0%;
left: 0%;
width: 100%;
height: 100%;
border-width: 2px;
} |
用 :before 和 :after 伪类结合更多 CSS3 强大的特性,还可以完成非常多有意思的特效和 Hack
资源链接 _ Learning To Use The :before And :after Pseudo-Elements In CSS _ The Shapes of CSS _ Pseudo-elements reference _ Add steps counter in form via CSS
文章作者 ZHIKING
上次更新 0001-01-01