How to Create a Pagination with CSS

Pagination is a crucial element in web design that allows you to break down large amounts of content into smaller, more manageable pieces.

This feature is essential for websites that have a lot of content, such as blogs, portfolios, or e-commerce stores.

In this tutorial, we will show you how to create a pagination with CSS.


Step 1: Define the HTML Structure

The first step in creating a pagination with CSS is to define the HTML structure. The HTML code should include the navigation elements and the page numbers. You can use an unordered list to define the navigation elements and each list item can contain a link to the corresponding page.

Here’s an example of HTML code:

<nav aria-label="Page navigation">
  <ul class="pagination">
    <li class="page-item">
      <a class="page-link" href="#">Previous</a>
    </li>
    <li class="page-item">
      <a class="page-link" href="#">1</a>
    </li>
    <li class="page-item">
      <a class="page-link" href="#">2</a>
    </li>
    <li class="page-item">
      <a class="page-link" href="#">3</a>
    </li>
    <li class="page-item">
      <a class="page-link" href="#">Next</a>
    </li>
  </ul>
</nav>

Step 2: Style the Pagination with CSS

The next step is to style the pagination with CSS. You can use CSS to change the appearance of the pagination, such as the background color, the font size, and the padding.

Here’s an example of CSS code:

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  list-style: none;
  padding: 0;
  margin: 0;
}

.page-item {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.5rem;
  margin: 0 0.5rem;
  border: 1px solid #ddd;
  border-radius: 0.25rem;
}

.page-link {
  color: #333;
  text-decoration: none;
}

Step 3: Add Interactivity with JavaScript

The final step is to add interactivity to the pagination with JavaScript.

You can use JavaScript to change the active page when the user clicks on a page number.

Here’s an example of JavaScript code:

var pagination = document.querySelector(".pagination");

pagination.addEventListener("click", function(event) {
  if (event.target.tagName === "A") {
    event.preventDefault();

    var pageLinks = pagination.querySelectorAll(".page-link");

    for (var i = 0; i < pageLinks.length; i++) {
      pageLinks[i].parentElement.classList.remove("active");
    }

    event.target.parentElement.classList.add("active");
  }
});