效果如上图所示,主要用到CSS3的伪类::after
、::before
,以及圆角边框border-radius
属性。对于下面的气泡框,能够有两种方式实现小三角:css
传统方式,利用CSS画小三角,利用到了透明背景和边框属性transparent
的应用。html
CSS3的transform
属性的使用字体
而后经过position
定位到合适的位置。url
此外,本文还会讲一下CSS的inherit
属性值的知识。spa
HTML结果也很简单,就一个DIV。下三角部分使用了CSS画三角的知识,
HTML:code
<div class="message1"> Demos 代码演示、代码片断 - 读你,欢迎来到读你,http://dunizb.com </div> <div class="message2"> Demos 代码演示、代码片断 - 读你,欢迎来到读你,http://dunizb.com </div>
CSS:orm
.message1,.message2 { width: 200px; height: 80px; margin: 100px auto; background-color: green; border-bottom-color:green;/*为了给after伪元素自动继承*/ color: #fff; font-size: 12px; font-family: Arial; line-height: 18px; padding: 5px 12px 5px 12px; box-sizing: border-box; border-radius: 6px; position: relative; word-break: break-all; } .message1::after { content: ''; position: absolute; top: 0; right: -24px; width: 20px; height: 20px; border-width: 0 0 20px 20px; border-style: solid; border-bottom-color: inherit; /*自动继承父元素的border-bottom-color*/ border-left-color: transparent; border-radius: 0 0 60px 0; } /** 经过对小正方形旋转45度解决 **/ .message2::before { content: ''; position: absolute; top: 50%; left: -5px; width: 10px; height: 10px; margin-top: -10px; background: inherit;/*自动继承父元素的背景*/ transform: rotate(45deg); } /** 经过画三角形解决 */ /*.message2::before {*/ /*content: '';*/ /*position: absolute;*/ /*top: 50%;*/ /*left: -20px;*/ /*width: 0px;*/ /*height: 0px;*/ /*margin-top: -10px;*/ /*border-width: 10px;*/ /*border-style: solid;*/ /*border-color: transparent green transparent transparent;*/ /*}*/
以上就是所有代码。
上面对小正方形使用了inherit属性值,经过把正方形旋转45度造成对外的三角而获得。htm
尽管绝大多数人都知道inherit这个关键字,可是不少人可能自始自终都没实际用过它,包括我本身,历来没有,在查询CSS文档时,习惯性的忽略它,直到看到《CSS揭秘》这本书。继承
inherit
能够用在任何CSS属性中,这从w3cschool文档中就已经体现了,它老是绑定到父元素的计算值(对伪元素来讲,则会取生成该伪元素的宿主元素)。举例来讲,要把表单元素的字体设定为与页面的其余部分相同,你并不须要重复指定字体属性,只须要利用inherit
的特性便可:rem
input,select,button { font: inherit }
与此相似,要把超连接的颜色设定为与页面中其余文本相同,仍是要用inherir
,好比下面的代码:
HTML:
<div class="article"> <p>Demos 代码演示、代码片断 - 读你 | 这世间惟有梦想和好姑娘不可辜负!</p> <a href="http://dunizb.com/demo/">Demos</a> </div>
CSS:
.article { font-family: "Microsoft YaHei"; font-size: 14px; color: red; }
效果:
此时文字的颜色是红色,而超连接默认是蓝色,并不会被改变,这是咱们都知道的,那么我想让超连接也是跟父元素同样的红色呢?此时咱们只须要给超连接inherit便可:
.article a { color: inherit; }
效果:
这个inherit对于背景色相同很是有用,可是须要注意的是,想要子元素设置属性的inherit关键字生效,父元素必须设置过使用inherit为值的属性。
与之相似的还有一个新的CSS颜色属性:currentColor
。这个属性是在CSS颜色(第三版)规范中新增长的,它是从SVG那里借鉴过来的,这个关键字并无绑定到一个固定的颜色值,而是一直被解析为color。实际上,这是CSS中有史以来第一个变量,虽然功能颇有限,但它真的是个变量。
举个例子,假如咱们想让全部的水平分割线(全部<hr>
元素)自动与文本颜色保持一致。
例如在上面的例子中添加水平线:
.article hr { height: .5em; }
默认状况下是这样的:
此时,添加 currentColor
.article hr { height: .5em; background: currentColor; }
效果:
当我在把文字颜色设为蓝色的时候,它们会保持跟文字颜色一致
参考资料:《CSS解密》[美]Lea Verou (做者) ,[中]CSS魔法 (译者),图灵教育,人民有点出版社