首页 > 解决方案 > CSS 掩码元素仅位于其顶部的位置

问题描述

我有一个包含一系列间隔文本元素的网页。

有一条绝对定位的线穿过这些文本元素,如下所示。

https://i.615283.net/u/vxDLVS.png

我需要它在文本元素内部被切断,因为在灰色区域内不可见的行。

在此处输入图像描述

现在不要立即回答,background: black;因为我需要显示的行后面有一个非黑色背景。

当元素在它前面时,有什么方法可以将线条掩盖起来根本不可见?

我的测试代码:

<div></div>
<p>Example textExample textExample textExample textExample textExample textExample textExample textExample textExample textExample textExample textExample textExample textExample textExample text</p>
p {
  text-align: center;
  margin: 45vh 0;
  z-index: 2;
  padding: 20vw;
  position: relative;
}

div {
  position: absolute;
  margin-left: calc(50vw - 1px);
  top: 0;
  width:2px;
  background: #cfc35d;
  height: 100vh;
}

注意:我不想使用原始像素值,因为这都是动态内容。

标签: css

解决方案


是的,CSS 伪元素可以做到

使用伪元素 :before 和 :after 可以做到这一点非常棒。

因为您可以绝对定位伪元素相对于它们的父元素,所以您可以将它们视为每个元素的两个额外层。

它们解锁了很多有趣的设计可能性,而不会对标记的语义产生负面影响。

* {
    margin:0px;
}
.wrapper {
    position: fixed;
    left: 0;
    width: 0;
    width: 100vh;
    height: 100vh;
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: center;
    font-size:20px;
    overflow:hidden;
}
.tagline {
    position:relative;
    width:150px;
    display:block;
    text-align:center;
}
.tagline:after, .tagline:before {
    content:'';
    width:5px;
    height:50vh;
    background:red;
    display: inherit;
    position:absolute;
    left:calc(50% - 5px)
}
.tagline:after {
    top:100%;
}
.tagline:before {
    bottom:100%;
}
<div class="wrapper">
  <div class="tagline"> Lorem ipsum dolor sit amet, consectetur adipiscing elit,</div>
</div>

在此处输入图像描述


推荐阅读