CSS,十二.transition的应用之CSS中心扩散

实现 css中心向两边扩散的两个核心

  • 1.hover 之前的 垂直居中
  • 2.文字置于最顶层
顺道来讲讲hover

伪元素是不支持 hover 的,不过我们可以给普通的 tag 标签添加 hover 以此来支持伪元素的 hover,例如 .div2:hover::before

顺道抬一手absolute

absolute有悬浮在元素上层的作用。

实现一

css

.wrap {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 60px;
    background-color: #6B7C7A;
    border-radius: 10px;
    color: #fff;
    cursor: pointer;
  }
  .box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 0;
    height: 60px;
    transition: all .8s;
  }
  .wrap:hover .box {
    width: 200px;
    border-radius: 10px;
    background-color: #000;
    transition: width .8s;
  }

html

  <div class="wrap">
    兄弟元素是一个div
    <div class="box"></div>
  </div>
  • 概述

    一个尚未成型的功能。

    通过 flex 的方式将文字居中。

    内嵌了一个空的 div 元素,并且设置为 absolute 使其不影响毗邻的 文字。

  • 待解决

    也许我们能够通过 伪元素 来改进使得不需要 多嵌入那一个 div。

    同时,文字的上排显示 也是我们需要解决的一个问题。


实现二

根据上面,A.我们可以利用伪元素来改进 多余的那个 div

B. 同时,我们通过对 文字 使用 absolute 来解决文字没有置顶的问题。

这里主要要注意的是 伪元素 没有 content 是不会出现的

css

  .wrap {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 60px;
    background-color: #6B7C7A;
    border-radius: 10px;
    color: #fff;
    cursor: pointer;
  }
  .wrap:before {
    content: '';
    width: 0;
    height: 60px;
    transition: all .8s;
  }
  .wrap:hover::before {
    width: 200px;
    border-radius: 10px;
    background-color: #000;
    transition: width .8s;
  }
  .box {
    position: absolute;
  }

html

<div class="wrap">
    <div class="box">现在文字出现在了内框</div>
</div>
  • 概述

    基本上实现了我们所需要的功能。双层结构。其实 删除了 多余的代码 之后,这种实现已经非常不错了。

  • 待解决

    文字置顶的方法或许可以改进 ? 不一定让其为 absolute?


等待未来更好的办法

那么我们来想想办法,不让文字被遮挡,或者说 -- 文字置顶。

父级的 absolute 主要是两个作用,一个是怕影响到文字,二是居中。A.其实,直接设置文字为 absolute 即可(孤掌难鸣)。 B.其实 flex 的布局方式已经实现了居中。