纯 CSS 实现带小箭头的评论框

要实现文章底部显示评论记录的功能,需求样式大致如下:

首先我们 UI 组件库使用的是 Element UI ,这里我们直接能想到用 Timeline 时间线组件就能满足要求,个别地方只需稍微改点样式代码就行了。

<el-timeline>
  <el-timeline-item
    :timestamp="dayjs(item.createdDate).format('YYYY-MM-DD HH:mm')"
    placement="top"
  >
    <el-card
      shadow="never"
      class="comment"
      :body-style="{ padding: '10px' }"
    >
      <div class="top">
        <span class="name">{{ comment.createdBy }}</span>
        <el-rate :max="10" :model-value="item.Score" disabled />
      </div>
      <div class="content">{{ comment.content}}</div>
    </el-card>
  </el-timeline-item>
</el-timeline>

我们这里不看其它无关的代码,直接看评论框,使用的是 card 组件,这里的内容区域的父元素是 class 为 el-card__body 的 DIV,我们只需要针对这个类写些样式就可以。

<style lang="scss" scoped>
:deep(.el-card__body) {
 position: relative;

 &::before {
   content: "";
   position: absolute;
   top: 20px;
   left: -6px;
   width: 10px;
   height: 10px;
   background: #fff;
   border-color: #e4e7ed;
   border-style: solid;
   border-width: 1px 0 0 1px;
   transform: rotate(-45deg);
 }
}
</style>

这里实现的方式是通过伪选择器 ::before 设置长宽和边框,进行 45 度旋转,然后相对于父元素进行绝对定位。

当我们打开开发者工具在元素项中把鼠标放到对应的元素上时,可以看到实际目标的区域。由于对 el-card__body 元素设置了 padding 值,这个箭头区域并不会遮住评论框里的内容。

但如果我们一定要去除这个遮挡部分,还有其它更好的方案吗?

评论

还没有评论...留下你的评论!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Sidebar