CSS - Indent list items
Asked Answered
B

2

7

Is there a way to indent each list-item using CSS?

So a normal list:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

Displays like so:

One
  Two
    Three
      Four
Bleachers answered 13/1, 2017 at 10:49 Comment(1)
nth-child selector with progressive values should help but that sounds like too bulky an approach. Sass/Less loops will help minimize the code that needs to be written but the end CSS (compiled) will still be bulky.Gabbro
T
9

Here you can use :before pseudo-element with transparent border. You can variate indent of list item by changing a width of pseudo-element. Along with that you can change list marker if set list-style: none; and set color of content

EDIT:

removed display: block and color: transparent and used space character \00a0 as a content.

li:before {
    float: left;
    content: "\00a0";
    width: 20px;
    border: 1px solid transparent;
}
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

The following one is little more complex with changed list marker (removed display: block as advised by @dippas, but border-top instead border didn't work for some reason)

ul {
   list-style: none;
   counter-reset: cnt;
}

li:before {
   float: left;
   counter-increment: cnt;
   content: counter(cnt)" \25b6";
   max-height: 100%;
   width: 29px;
   border: 1px solid transparent;
   margin-top: -.1em;
   color: green;
}
<ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
      <li>Four</li>
    </ul>
Tinea answered 13/1, 2017 at 11:5 Comment(4)
Damn thats cleverBleachers
this is nice trick, but can be improved, only needs border-top and no need display:blockRegardless
@Regardless I've append one more variant according to your notesTinea
@Tinea it worked in FF, don't know which browser are you usingRegardless
R
4

If you have a lot of list-items,then the answer given by @Banzay is cleaner, but if you just have few of them, you can use nth-child for that

li:first-child {
  margin-left: 10px
}
li:nth-child(2) {
  margin-left: 20px
}
li:nth-child(3) {
  margin-left: 30px
}
li:nth-child(4) {
  margin-left: 40px
}
/*just demo*/

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>
Regardless answered 13/1, 2017 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.