before和after伪元素的使用(遮罩)

892 阅读1分钟

before和after伪元素做遮罩层

::before

  1. 他是一个盒子,是用css创建出来的。
  2. 他是一个行内元素,直接设置宽高无效。
  3. 他是一个孩子。 .box::before{} 这个 before伪元素是box 的一个子元素(孩子)
  4. 他是放到box盒子内容的最前面

::after

  1. 他是一个盒子,是用css创建出来的。
  2. 他是一个行内元素,直接设置宽高无效。
  3. 他是一个孩子。 .box::after{} 这个 after伪元素是box 的一个子元素(孩子)
  4. 他是放到box盒子内容的最后面
 /* 伪元素  before .... 之前 */
.box::before {
    /* 必须要写的属性 content */
    content: '我是';
    background-color: purple;
    width: 100px;
    height: 100px;
}

/* 伪元素  after .... 之后 */
.box::after {
    /* 必须要写的属性 content */
    content: '你呢?';
    background-color: skyblue;
    width: 100px;
    height: 100px;
}

那么用作遮罩层的时候怎么写呢?借助于定位,一定要给宽度和高度哦~

盒子显示和隐藏

css 做的显示和隐藏主要做一些装饰类的效果。 比如显示隐藏遮罩层。

都是用 display: none 和 display: block 来做的。

css部分代码块分享

.box {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: pink;
    margin: 100px auto;
}

/* 伪元素默认的是行内元素 */
.box::before {
    /* 隐藏的  不占位置 */
    display: none;
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

/* 鼠标经过box,显示的是 before */
.box:hover::before {
    /* 显示出来 */
    display: block;
}

box盒子原先处于隐藏状态,当鼠标经过就block