Horizontally scrollable list of cards in Bootstrap

2019-02-03 10:31发布

问题:

I am trying to create a horizontal list of cards where 3 cards are shown at a time and the other ones are horizontally scrollable, like this:

This can be done with CSS pretty easily, but I want to do this using Bootstrap. Bootstrap 4 ships with cards as popularized by material design and they are as easy to use as anything else in Bootstrap. For this example instead of cards it could also be regular divs.

The thing I am struggling with is creating a scrollable container of X cards (or divs) where 3 of them are shown at a time and the others overflow to the right and are scrollable. I am not sure how to use Bootstrap give the cards (or divs) a width so that 3 are shown at a time and the other ones lie next to them on the right.

回答1:

Now that Bootstrap 4 Alpha 6 uses flexbox, this horizontal scrolling layout is much easier. You can simply use flex-row and flex-nowrap:

<div class="container-fluid">
    <div class="row flex-row flex-nowrap">
        <div class="col-3">
            <div class="card card-block">Card</div>
        </div>
        <div class="col-3">
            <div class="card card-block">Card</div>
        </div>
        <div class="col-3">
            <div class="card card-block">Card</div>
        </div>
        <div class="col-3">
            <div class="card card-block">Card</div>
        </div>
        ...
    </div>
</div>

https://www.codeply.com/go/GoFQqQAFhN

Update 2018 Bootstrap 4.0.0

The above method still works, or you can use the flexbox utils in the container of the cards: https://www.codeply.com/go/PF4APyGj7F



回答2:

You can use bootstrap-horizon

Installation

Include bootstrap-horizon.css after bootstrap.css

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="/bower_components/bootstrap-horizon/bootstrap-horizon.css">

Add the .row-horizon class to .rows that require horizontal scrolling. In order to improve the UX, bootstrap-horizon overrides bootstrap's .col-*-* classes to make the baseline width 90% instead of 100% which allows for a small portion of the last column to be displayed.

<div class="row row-horizon">
  <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
    ...
  </div>
</div>

Example