Maison  >  Article  >  interface Web  >  使用::before和::after来完成尖角效果_html/css_WEB-ITnose

使用::before和::after来完成尖角效果_html/css_WEB-ITnose

WBOY
WBOYoriginal
2016-06-24 11:36:212006parcourir

一、目标

目标完成下图效果:

二、完成

1、分析

在::before和::after伪元素的用法一文中有说到使用::befrore和::after可以完成一个六边形。这个案例是用一个#star-six完成一个正三角形,通过::after实现一个倒三角形,然后绝对定位放好位置。我们接下来也用这个思路完成。

2、完成

第一步,先完成如下基本的效果,实现一个在浏览器中居中的文本

代码如下:

<style>.middle{text-align:center;}.title{background-color:black;color:#f3e14f;display:inline-block;font-size:18px;height:40px;line-height:40px;padding:0 50px;}</style><div class="middle"><h5 class="title">升级有好礼</h5></div>

第二步,做左右两边尖尖的效果。可以根据做五角星的代码修改。

代码如下:

<style>#star-three {  width: 0;  height: 0;  border-left: 100px solid transparent;  border-top: 50px solid red;  border-bottom: 50px solid red;/*  position: relative;*/}</style><div id="star-three"></div>

第三步,通过::before来实现第二步中的效果。

代码还是第二步中的代码,但是是通过::before来实现记得写上content:""。然后调整一下尺寸。

.title::before{  width: 0;  height: 0;  border-left: 40px solid transparent;  border-top: 20px solid red;  border-bottom: 20px solid red;  content: "";}

如果给border-left设置蓝色会发现效果如下。【原理还不是很懂,不知道这个高度是因为什么原因??】

结果这是什么鬼?不是想要的效果。此时需要调整布局。

第四步,使用绝对定位调整布局。

.title设置relative,.title::before设置absolute。效果如下。

第五步,通过left调整。

.title{background-color:black;color:#f3e14f;display:inline-block;font-size:18px;height:40px;line-height:40px;position:relative;padding:0 50px;}.title::before{  width: 0;  height: 0;  border-left: 40px solid transparent;  border-top: 20px solid red;  border-bottom: 20px solid red;  content: "";  position:absolute;  left:-40px;}

第六步,同理,通过::after实现右边效果。

.title::after{  width: 0;  height: 0;  border-right: 40px solid transparent;  border-top: 20px solid red;  border-bottom: 20px solid red;  content: "";  position:absolute;  right:-40px;}

第七步,改下颜色就好了。

完整代码如下:

<!DOCTYPE html><html><head><meta charset="utf-8"/><title>demo of starof</title><style>.middle{text-align:center;}.title{background-color:black;color:#f3e14f;display:inline-block;font-size:18px;height:40px;line-height:40px;position:relative;padding:0 50px;}.title::before{  width: 0;  height: 0;  border-left: 40px solid transparent;  border-top: 20px solid black;  border-bottom: 20px solid black;  content: "";  position:absolute;  left:-40px;}.title::after{  width: 0;  height: 0;  border-right: 40px solid transparent;  border-top: 20px solid black;  border-bottom: 20px solid black;  content: "";  position:absolute;  right:-40px;}</style></head><body><div class="middle">  <h5 class="title">升级有好礼</h5></div></body></html>

效果

 

本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:有问题欢迎与我讨论,共同进步。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn