Let’s build a dismissible card without any custom JavaScript and only with Bootstrap CSS classes.
the combination of card-header
, the Bootstrap 4 Close Icon and negative margins (here .mt-n5
) on the card-body
. The close icon gets nicely positioned within the card-header and the negative margins pull the card content closer into the header area.
<div class="container">
<div id="closeablecard" class="card card-hover-shadow mt-4">
<div class="card-header bg-transparent border-bottom-0">
<button data-dismiss="alert" data-target="#closeablecard" type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body mt-n5">
<h5 class="card-title">Your Title</h5>
<p class="card-text">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatem recusandae voluptate porro suscipit numquam distinctio ut. Qui vitae, ut non inventore necessitatibus quae doloribus rerum, quaerat commodi, nemo perferendis ab.
</p>
<a href="#" class="card-link">Card link</a>
<a href="#" class="card-link">Another link</a>
</div>
</div>
</div>
To actually close the card we can make use of the BS4 Data-API and put the the following data attributes in the button tag: data-dismiss="alert" data-target="#closeablecard"
. data-target is the ID of our card and data-dismiss=alert triggers the actual close event in Bootstrap.
For BS5, make changes to data-* attributes. see below;
<button data-bs-dismiss="alert" data-bs-target="#closeablecard" type="button" class="close float-end" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
References
https://stackoverflow.com/questions/43970878/how-to-add-close-button-to-bootstrap-card
https://stackoverflow.com/questions/23873005/hide-div-by-default-and-show-it-on-click-with-bootstrap