li元素文本溢出后,::before伪元素出现意外的顶部空间

4
我有一个列表组件,其中定义了一个自定义符号作为before伪元素:
li:before {
  display: inline-flex;
  width: .8rem;
  height: .8rem;
  margin-right: 1.5rem;
  margin-left: -2.9rem;
  background-color: #00c878;
  border-radius: .375rem;
  content: "";
}

只要li的内容不超出容器,就一切正常。但是,如果内容溢出容器,整个内容会向下跳动几个像素,并留下奇怪的顶部间距,这时就会出现问题。

enter image description here

我已经在这里重新创建了它。

我成功地使用work-break: break-all使其消失,但这当然不是一个可持续的解决方案。

有什么建议吗?


如果您移除负边距,您将看到这个技巧,您需要在此处考虑使用position:absolute来处理这个符号。 - Temani Afif
如果您不希望它们溢出,则 white-space: nowrap; 可能会有所帮助。 - Miloš Miljković
请在此处添加HTML,以便我们有更多内容可供使用。请注意,您可以在问题中使用代码片段来替换fiddle。 - Mark Schultheiss
2个回答

2

有很多解决方案,但这个是最好的

请在伪元素上设置绝对定位并删除边距。我的解决方案使用定位来自动对齐换行后的文本。

优点:

  • 非常紧凑的代码
  • 适用于任何字体大小
    (不包含绝对像素值)
  • 完美对齐每一行
    (第一行和后面的行之间没有微小偏移)

.container {
  width:170px;
  border:1px solid red;
}
ul {
  margin: 0;
  padding: 0;
}
li {
  padding-left: 35px;
  margin-bottom: 24px;
  margin-top: 0;
  font-size: 16px;
  line-height: 24px;
  list-style-type: none;
  position:relative;
  word-break: break-all;
}
 li::before {
  width: 4px;
  height: 4px;
  background-color: #00c878;
  border-radius: 375px;
  content: "";
  position: absolute;
  left: 10px;
  top: 9px;
}
<div class="container">
    <div class="list unordered">
        <h3 class="text-grey-150 h5 "> Branchen ETFs </h3>
        <ul class="">
            <li>Technologie ETF
                <br>
            </li>
            <li style="/* word-break: break-all; */">Finanzdienstleistungen ETF</li>
            <li>Gesundheitswesen ETF
                <br>
            </li>
            <li>Immobilien ETF
                <br>
            </li>
            <li>Industrie ETF</li>
        </ul>
    </div>
</div>


1

当使用自定义伪元素时,最好将它们相对于 li 进行绝对或相对定位。请参见下面的示例,这样可以解决您的问题:

li {
  padding-left: 35px;
  margin-bottom: 24px;
  margin-top: 0;
  font-size: 16px;
  line-height: 24px;
  list-style-type: none;
  position: relative;
}

li::before {
  display: inline-flex;
  width: 4px;
  height: 4px;
  margin-right: 15px;
  margin-left: -29px;
  background-color: #00c878;
  border-radius: 375px;
  content: "";
  position: absolute;
  top: 9px;
}  

你可以使用 topleft 属性来根据需要重新定位。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接