Unexpected top space when li element text is overflowing after ::before

Viewed 249

I have a list component with a custom bullet defined as a before pseudoelement:

li:before {
  display: inline-flex;
  width: .8rem;
  height: .8rem;
  margin-right: 1.5rem;
  margin-left: -2.9rem;
  background-color: #00c878;
  border-radius: .375rem;
  content: "";
}

It all works fine as long as the li content doesn't overflow the container. Then, the whole content just jumps down a few pixels and leaves a weird top margin between the bullet and the content.

enter image description here

I have recreated it here.

I have managed to make it disappear using work-break: break-all, but that is of course not a susteinable solution.

Any tips?

2 Answers

So many solutions. but this one worked best

Please Set position to absolute on the pseudo element and remove margin. My solution uses positioning to get wrapped lines automatically line up correctly.

Advantages:

  • very compact code
  • works with any font size
    (no absolute pixel values contained)
  • aligns rows perfectly
    (no slight shift between first line and following lines)

.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>

When doing custom pseudo-elements it's better to position them absolute and relative to the li. See example below, this has fixed your issue:

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;
}  

You can use top and left properties to re-position as per your needs.

Related