How to Transform a Basic List into a List Group with CSS?

A list group is a common UI pattern used to display a collection of related items, often with additional styling to visually group them together.

Table of Content

  • Using CSS Classes
  • Using CSS Selectors

Using CSS Classes

This approach uses CSS classes to style the list items and create a cohesive list group. By applying a specific class to the list container, we remove default list styles and set padding to ensure uniformity. Then, each list item within the container inherits these styles while receiving additional stylings such as background color and border, resulting in visually distinct and organized groupings of list items.

Example: Implementation to transform a basic list into a list group using CSS classes.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>
          List Group with CSS Classes
      </title>
    <style>
        .list-group {
            list-style: none;
            padding: 0;
        }

        .list-group li {
            background-color: #f4f4f4;
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
    </style>
</head>

<body>
    <ul class="list-group">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</body>

</html>

Output:

Using CSS Selectors

In this approach, CSS selectors are used to style list items differently based on their attributes or classes. By applying specific styles to elements with certain classes or pseudo-classes like “:not()”, we can create visually distinct groupings within the list. This method offers flexibility in styling individual list items based on their relationships or attributes, enhancing the overall presentation of the list group.

Example: Implementation to transform a basic list into a list group using CSS Selectors.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>
          List Group with 
          CSS Selectors
      </title>
    <style>
        ul {
            list-style: none;
            padding: 0;
        }

        ul li.group-start {
            background-color: #007bff;
            color: #fff;
            font-weight: bold;
            padding: 10px;
        }

        ul li:not(.group-start) {
            padding: 10px 10px 10px 30px;
            border-bottom: 1px solid #ddd;
        }
    </style>
</head>

<body>
    <ul>
        <li class="group-start">Group 1</li>
        <li>Item 1</li>
        <li>Item 2</li>
        <li class="group-start">Group 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ul>
</body>

</html>

Output: