| Pinterest's card layout has become quite popular due to its visually appealing and responsive nature. In this tutorial, we'll create a similar layout using Bootstrap 5 and Masonry. Prerequisites Before we start, make sure you have Bootstrap and Masonry included in your project. <!-- Bootstrap 5 CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
<!-- Masonry CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.css" rel="stylesheet">
HTML Structure First, let's set up our HTML structure. We'll create a container with rows and columns where each column represents a card. <div class="container">
<div class="row" id="masonry-grid">
<div class="col-md-4 mb-3">
<div class="card">
<img src="image1.jpg" class="card-img-top" alt="Image 1">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
</div>
</div>
<!-- More columns -->
</div>
</div>
JavaScript Initialization Now, let's initialize Masonry on our grid container. We'll set the column width and gutter to ensure proper alignment. <script src="https://cdnjs.cloudflare.com/ajax/libs/masonry/4.2.2/masonry.pkgd.min.js"></script>
<script>
var grid = document.getElementById('masonry-grid');
var masonry = new Masonry(grid, {
itemSelector: '.col-md-4',
columnWidth: '.col-md-4',
gutter: 30
});
</script>
Making it Responsive To ensure our layout adjusts properly on different screen sizes, we'll need to re-layout Masonry on window resize. <script>
window.addEventListener('load', function() {
var masonry = new Masonry(grid, {
itemSelector: '.col-md-4',
columnWidth: '.col-md-4',
gutter: 30
});
});
window.addEventListener('resize', function() {
masonry.layout();
});
</script>
Finishing Touches Finally, let's add some CSS to adjust the spacing and appearance of our cards. #masonry-grid .card {
width: 100%;
}
#masonry-grid .card-img-top {
width: 100%;
height: auto;
}
#masonry-grid .card-body {
padding: 1rem;
}
And there you have it! You now have a Pinterest-style card layout using Bootstrap and Masonry. Feel free to customize the content and styles to match your project requirements. |