首页 > 应用开发 > IT综合 > 好程序员web前端培训系列分享css伪元素的实用技巧
好程序员 web 前端培训系列分享 css 伪元素的实用技巧
在CSS2之前规范不明确的时,伪元素使用单冒号(:)来表示;
在CSS3规范中的要求使用双冒号(::)表示伪元素,以此来区分伪元素和伪类;但为了向上兼容,现在用单冒号(:)也可以的。
下面运用before和after在元素前面和后面插入伪元素,实现一些有意思的小效果,代码和效果图附上。
3.1用伪元素实现插入文字、字体图标库
3.1.1插入文字:
h1 :before {
content : "你好" ; /* 在标题前面插入文字 并设置样式 */
color : pink ;
font-size : 20 px ;
width : 40 px ;
height : 40 px ; }
< h1 > 我是标题 </ h1 >
效果如下:
3.1.2插入iconfont字体图标库:
@ font-face {
font-family : 'iconfont' ;
src : url ( 'http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.eot' );
src : url ( 'http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.eot?#iefix' ) format ( 'embedded-opentype' ),
url ( 'http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.woff2' ) format ( 'woff2' ),
url ( 'http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.woff' ) format ( 'woff' ),
url ( 'http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.ttf' ) format ( 'truetype' ),
url ( 'http://at.alicdn.com/t/font_1274897_t3pj4anz7hg.svg#iconfont' ) format ( 'svg' ); }
h1 :before {
font-family : "iconfont" !important ;
/* 一定要加 */
content : "\e601" ;
color : pink ;
font-size : 20 px ;
width : 40 px ;
height : 40 px ;}
< h1 > 我是标题 </ h1 >
根据效果图可以看到伪元素是inline元素类型
3.2清除浮动
解决浮动导致的父元素高度塌陷的问题
. clear :after {
content : "" ;
display : block ;
clear : both ;
}
ul {
background : pink ;
}
li {
float : left ;
margin : 0 20 px ;}
< ul class = "clear" >
< li > hello world </ li >
< li > hello world </ li >
< li > hello world </ li >
< li > hello world </ li >
</ ul >
3.3分割线效果
p :before{
content : '' ;
display : inline-block ;
width : 100 px ;
height : 2 px ;
background : pink ;
margin : 5 px ;
}
p :after{
content : '' ;
display : inline-block ;
width : 100 px ;
height : 2 px ;
background : pink ;
margin : 5 px ;
}
< p > 分割线 </ p >
效果图:
3.4对话框效果
div {
width : 180 px ;
height : 36 px ;
line-height : 36 px ;
background : #c0eeff ;
border-radius : 5 px ;
font-size : 14 px ;
text-align : center ;
position : relative ;}
div :before {
content : "" ;
position : absolute ;
top : 10 px ;
left : -14 px ;
/* 画三角形 */
width : 0 ;
height : 0 ;
border-top : 10 px solid transparent ;
border-right : 20 px solid #c0eeff ;
border-bottom : 10 px solid transparent ;
border-left : 0 solid #c0eeff ;
}
< div > 快来和我聊天吧 ~</ div >
效果图如下:
3.5 相片层叠效果
div {
width : 400 px ;
height : 300 px ;
border : 8 px solid #eee ;
position : relative ;}
div img {
width : 100 % ;
height : 100 % ;}
div :before , div :after {
content : "" ;
position : absolute ;
top : 0 ;
left : 0 ;
z-index : -1 ;
width : 400 px ;
height : 300 px ;
border : 8 px solid #eee ;
transform : rotate ( 8 deg );}
div :after {
transform : rotate ( -8 deg );}
< div >
< img src = "https://gitee.com/ay8yt/imageStore/raw/master/%E4%BA%8C%E9%98%B6%E6%AE%B5%E5%A4%A7%E7%BA%B2/%E5%9B%BE%E7%89%87/QQ%E6%88%AA%E5%9B%BE20200417104911.png" ></ div >
效果图如下:
使用伪元素能实现的效果非常多,也可以减少网页中标签的使用,一起动手试试看伪元素的妙用技巧吧。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69913864/viewspace-2688473/ ,如需转载,请注明出处,否则将追究法律责任。