The most popular techniques for adding spacing between list items in CSS include the following:
Using Margin
You can add space between the list items by using the margin attribute. Use the following CSS, for instance, to add 5px of space between list items:
li {
margin: 5px;
}
Additionally, you can add spacing to particular list item sides by using the margin-top, margin-right, margin-bottom, and margin-left attributes.
Using Padding
You can add space between the list items using the padding attribute. Use the following CSS, for instance, to add 5px between list items.
li {
padding: 5px;
}
Additionally, you can add spacing to particular edges of the list items with the padding-top, padding-right, padding-bottom, and padding-left attributes.
Using nth-child
By specifying the nth-child, you can provide space between list items on a selective basis. As an illustration, this will give all list items—aside from the first one—a margin-top of 5 pixels.
li:nth-child(n+2) {
margin-top: 5px;
}
This CSS code selects all list items that are the second or later child of a parent element and applies a top margin of five pixels to them. The selector li:nth-child(n+2) is used to select every li element that is the second child or later of its parent element. The margin-top style is setting the top margin of selected elements to 5 pixels. This will add 5 pixels of space between the top of the list items and the element above them.
Using list-style
By setting the list-style-type property to none and then using the padding or margin property to provide spacing, you can use the list-style property to regulate the distance between list items. For instance:
ul {
list-style-type: none;
}
li {
padding: 5px;
}
The above rule will remove the dots in front of list items and will give the padding of 5px around them. The first CSS rule, ul { list-style-type: none; }, removes the default bullet point marker from each list item. The second CSS rule, li { padding: 5px; }, adds padding to all sides of each list item.