CSS“溢出:hidden;”仍然适用于伪“::after”

axr492tv  于 2023-04-13  发布在  其他
关注(0)|答案(3)|浏览(119)

::after中的content: '>';overflow: hidden;裁剪

.centered-text {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 30vw;
}

.centered-text::before {
  content: '<';
}

.centered-text::after {
  content: '>';
}
<div style="text-align:center;">
  <span style="float:left;">I'm on the left</span>
  <span class="centered-text">a brown fox jumps over the lazy dog</span>
  <span style="float:right;">I'm on the right</span>
</div>

结果:

I'm on the left         <a brown fox jumps over th...          I'm on the right

::after中的'>'被剪裁。
我所期望的是“〉”仍然可见。

I'm on the left         <a brown fox jumps over th...>         I'm on the right

我已经将overflow: visible;添加到::after中以覆盖.centered-text中的overflow: visible;,但是'〉'仍然被裁剪。

kr98yfug

kr98yfug1#

.centered-text::after被认为是.centered-text的子元素,这意味着当它涉及到overflow: hidden时,它将被视为正常的实际子元素。
一个解决方案是将文本 Package 在另一个元素中,并对其应用样式:

<div>
  <span>...</span>
  <span class="centered-text">
    <span>a brown fox jumps over the lazy dog</span>
  </span>
  <span>...</span>
</div>
.centered-text span {
  /* ... */
}

试试看:

.centered-text span {
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 30vw;
}

.centered-text::before {
  content: '<';
}

.centered-text::after {
  content: '>';
}
<div style="text-align:center;">
  <span style="float:left;">I'm on the left</span>
  <span class="centered-text">
    <span>a brown fox jumps over the lazy dog</span>
  </span>
  <span style="float:right;">I'm on the right</span>
</div>
pnwntuvh

pnwntuvh2#

你可以使用一个css变量,使用绝对位置,并通过javascript设置css变量。

const centeredText = document.getElementsByClassName('centered-text')[0]
const rect = centeredText.getBoundingClientRect()
document.documentElement.setAttribute("style", "--right-arrow-width: "+ rect.right+"px");
:root {
  --right-arrow-width: 0px;
}
.centered-text {

    box-sizing: content-box;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 30vw;
}
.centered-text::before {
    content: '<';
}
.centered-text::after {
      content: '>';
      left: var(--right-arrow-width);
      position: absolute;
}
<body>
    <div style="text-align:center;">
        <span style="float:left;">I'm on the left</span>
        <span class="centered-text">a brown fox jumps over the lazy dog</span>
        <span style="float:right;">I'm on the right</span>
    </div>
</body>
cl25kdpy

cl25kdpy3#

@InSync谢谢!如果我将消息缩短为<span>a brown fox</span>,则额外 Package 器的问题是lots of spaces and disalignment of '<>'

相关问题