Search code examples
csshtml-liststext-align

Customized counter ordered list alignment issue


I have a simple ordered list. I used counter-reset property to change the styles for number. But the issue is when the container (.list) width is small the list doesn't align directly like an ordered list should do.

.list{
  border: 1px solid black;
  width: 40%;
  box-sizing: border-box;
}
ol{
  list-style: none;
  counter-reset: csscounter;
  padding-left: 0.5rem;
}

li{
    counter-increment:csscounter;
    margin-bottom: 0.25rem;
}
li:before{
  content: counter(csscounter);
  background: gray;
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 100%;
  display: inline-block;
  line-height: 1.5rem;
  text-align: center;
  color: white;
  margin-right: 0.5rem;
}
<div class='list'>
<ol>
  <li>
    Enter your mobile number to view  your book collection
  </li>
  <li>
    Select the books that you want to add to your collection
  </li>
  <li>
    Confirm and Submit
  </li>
</ol>
</div>

If I remove the css properties for <ol> the list renders correctly and no alignment issues occurs.

.list{
  border: 1px solid black;
  width: 40%;
  box-sizing: border-box;
}
<div class='list'>
<ol>
  <li>
    Enter your mobile number to view  your book collection
  </li>
  <li>
    Select the books that you want to add to your collection
  </li>
  <li>
    Confirm and Submit
  </li>
</ol>
</div>


Solution

  • The <ul> has different paddings.

    enter image description here

    The problem is that you introduced a ::before pseudo element. You have to rework your paddings and margins.

    .list {
      border: 1px solid black;
      width: 40%;
      box-sizing: border-box;
    }
    
    ol {
      list-style: none;
      counter-reset: csscounter;
      padding-left: 2rem;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
    }
    
    li {
      counter-increment: csscounter;
      margin-bottom: 0.25rem;
    }
    
    li:before {
      content: counter(csscounter);
      background: gray;
      width: 1.5rem;
      height: 1.5rem;
      border-radius: 100%;
      display: inline-block;
      line-height: 1.5rem;
      text-align: center;
      color: white;
      margin-left: -1.75rem;
    }
    <div class="list">
      <ol>
        <li>
          Enter your mobile number to view your book collection
        </li>
        <li>
          Select the books that you want to add to your collection
        </li>
        <li>
          Confirm and Submit
        </li>
      </ol>
    </div>