隐藏溢出文本后面的文本

问题描述 投票:0回答:2

我想知道如何隐藏被其他文本溢出的文本。

看看这个例子:

.container {
  display: flex;
}

.left {
  background-color: red;
  width: 50px;
  overflow: visible;
  /* should be position relative but I'm omitting it just for this example */
}

.left p {
  position: absolute;
  left: 15px;
}

.right {
  background-color: tan
}
<div class="container">
  <div class="left">
    <p>text text text</p>
  </div>
  <div class="right">
    <p>123456</p>
  </div>
</div>

如您所见,左侧 div 的文本溢出到右侧 div 的文本中。如何使用 CSS 使左侧文本与右侧文本重叠,以便重叠的右侧文本根本不显示?我需要保留当前的 html 结构和溢出的文本。

我通常会在左侧文本上使用背景颜色,但在这种特殊情况下,我不能使用背景颜色,因为它延伸出了其父 div。

html css
2个回答
2
投票

您可以考虑一个伪元素,您将使用右侧 div 的背景颜色来隐藏文本。然后调整元素的

z-index
以获得想要的效果:

.container {
  display: flex;
  z-index:0;
  margin:5px;
}

.left {
  background-color: red;
  width: 50px;
  overflow: visible;
  /* should be position relative but im omitting it just for this example */
}

.left p {
  position: absolute;
  left: 15px;
}

.left p:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:tan;
}

.right {
  background-color: tan;
  z-index:-2;
}
<div class="container">
  <div class="left">
    <p>text text text</p>
  </div>
  <div class="right">
    <p>123456</p>
  </div>
</div>

<div class="container">
  <div class="left">
    <p>text </p>
  </div>
  <div class="right">
    <p>123456</p>
  </div>
</div>
<div class="container">
  <div class="left">
    <p>text text aa </p>
  </div>
  <div class="right">
    <p>123456</p>
  </div>
</div>


0
投票

您可以通过在

<p>
上应用背景颜色和一些右侧填充以使其更清晰来实现此目的。

.container {
  display: flex;
}

.left {
  background-color: red;
  width: 50px;
  overflow: visible;
  /* should be position relative but im omitting it just for this example */
}

.left p {
  position: absolute;
  left: 15px;
  background-color: red;
  padding-right:0.25em;
}

.right {
  background-color: tan
}
<div class="container">
  <div class="left">
    <p>text text text</p>
  </div>
  <div class="right">
    <p>123456</p>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.