HTML 中使用 CSS3 实现气泡提示效果,可以使用伪类选择器和 CSS3 的transform属性进行实现。具体步骤如下:
在HTML中添加需要添加气泡提示效果的元素,例如:
使用 CSS 为该元素设置样式,例如:给元素添加position属性(以便定位),设置宽度、高度、背景色等基本样式。
使用伪类选择器:before或:after添加一个伪元素,用于创建气泡形状(这里以:before为例):
.bubble:before{
content:"";
position:absolute;
width:0;
height:0;
border-width:10px;
border-style:solid;
border-color:transparent transparent #fff transparent;
transform:translateX(-50%);
left:50%;
bottom:100%;
}
其中,content属性为必需属性,指定伪元素的内容为空;position属性设置为absolute,因为伪元素是相对于包含块而言定位的,比如body或有固定尺寸的父元素;border-*属性用于设置边框宽度、样式和颜色;transform属性用于平移伪元素使其水平居中;left和bottom属性用于定位,设置百分数值可适配不同宽度的父元素,此处left为50%时,表示将伪元素定位到距离包含块左边界50%的位置。
.bubble:before{
background-color:#fff;
box-shadow:0 2px 5px rgba(0,0,0,0.3);
border-radius:2px;
}
这里以设置背景色和box-shadow阴影为例。边缘圆角半径可使用border-radius属性设置。
.bubble{
position:relative;
display:inline-block;
padding:10px;
color:#333;
}
.bubble:before{
content:"";
position:absolute;
width:0;
height:0;
border-width:10px;
border-style:solid;
border-color:transparent transparent #fff transparent;
transform:translateX(-50%);
left:50%;
bottom:100%;
background-color:#fff;
box-shadow:0 2px 5px rgba(0,0,0,0.3);
border-radius:2px;
}
注意,在 CSS 中利用前缀提供更好的浏览器兼容性是一个好习惯:例如,如果要兼容旧版Webkit、FF Gecko和米诺布+Opera浏览器,您可以此样式:
.bubble:before {
content:"";
position:absolute;
left: 50%;
margin-left:-15px;
width:0px;
height:0px;
border-top:15px solid transparent;
border-bottom:15px solid #fff;
border-left:15px solid #fff;
transform-origin:0 0;
transform:rotate(45deg);
-moz-transform:rotate(45deg);
-webkit-transform: rotate(45deg);
-o-transform:rotate(45deg);
}
这里使用了CSS3提供的transform属性,将伪元素旋转45度。