How to Add Sort Indicator Arrows to Bootstrap Table

Bootstrap helps to opt-in styling of HTML tables quickly. You can create a nice looking HTML table within a minute using the Bootstrap framework. Bootstrap table design can be enhanced easily using minimal CSS.

The column sorting is a commonly used feature on the web application. To add the column sorting functionality, the HTML table style needs to be changed. If you are using the Bootstrap table structure, sort indicator icons can be easily added to the columns. In this tutorial, we will show you how to add sort indicator arrows to Bootstrap table columns using CSS.

The following example code snippet adds up/down arrow icons to table columns that help sort records by asc/desc order.

HTML Code:

<div class="container">
    <h2 class="page-header">Bootstrap Table with Sort Indicators</h2>

    <table class="table table-bordered table-sortable">
        <caption>
            <code>table.table-sortable</code>
        </caption>
        <thead>
            <tr>
                <th class="asc">#</th>
                <th class="desc">Field 1</th>
                <th>Field 2</th>
                <th>Field 3</th>
            </tr>
        </thead>
        <tbody>
            <tr><th scope="row">1</th><td>Data 1</td><td>John</td><td>2020-01-24</td></tr>
            <tr><th scope="row">2</th><td>Data 2</td><td>Andrew</td><td>2020-01-22</td></tr>
            <tr><th scope="row">3</th><td>Data 3</td><td >Laura</td><td>2020-01-20</td></tr>
        </tbody>
    </table>
</div>

CSS Code:

h2.page-header {
    margin-top: 0px;
    padding-top: 0px;
    line-height: 15px;
    vertical-align: middle;
}

.table-sortable > thead > tr > th {
    cursor: pointer;
    position: relative;
}

.table-sortable > thead > tr > th:after,
.table-sortable > thead > tr > th:after,
.table-sortable > thead > tr > th:after {
    content: ' ';
    position: absolute;
    height: 0;
    width: 0;
    right: 10px;
    top: 16px;
}

.table-sortable > thead > tr > th:after {
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #ccc;
    border-bottom: 0px solid transparent;
}

.table-sortable > thead > tr > th:hover:after {
    border-top: 5px solid #888;
}

.table-sortable > thead > tr > th.asc:after {
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 0px solid transparent;
    border-bottom: 5px solid #333;
}
.table-sortable > thead > tr > th.asc:hover:after {
    border-bottom: 5px solid #888;
}

.table-sortable > thead > tr > th.desc:after {    
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #333;
    border-bottom: 5px solid transparent;
}

RELATED HOW TO GUIDES

Leave a reply

keyboard_double_arrow_up