How can I show 3 items per row in Vuejs?
Problem
I have a use case in vue.js where I have multiple items which are basically cards, now I want to show them in rows where each row has 3 cards, Below is the way I tried(I have removed the to shorten the code).
<template> <div class="container" @scroll="handleScroll"> <div class="card-container"> <!-- Loop through the products data and display cards horizontally --> <AddCourseCard />
<CoursesCard v-for="(item, index) in dummyData" :key="index" :title="item.title" :text="item.text" :imageSrc="item.imageSrc" class="card" /> </div> </div> </template>
<style scoped> .container { display: flex; justify-content: center; /* Added to enable scrolling */ overflow-y: auto; }
.card-container { display: flex; flex-wrap: wrap; justify-content: center; /* Center the cards horizontally */ gap: 10px; max-width: 1216px; /* Set a max-width for the container */ margin: 0 auto; /* Center the container horizontally */ }
.card { flex: 0 0 calc(33.33% - 10px); max-width: calc(33.33% - 10px); margin-bottom: 20px; box-sizing: border-box; /* Include padding and border in card width */ } </style> |
Here I have to render AddCourseCard only when the user is admin, it will render as the first element, if a user is not admin, the original list will start rendering as usual.
Now the problem is that if I have 7 elements here, the 7th will go in the 3rd row and ideally should be at the first position of the 3rd row but it gets in the middle of the third row which looks very weird.
does anyone know a fix for this or any other better ways to do this?
Solution
Try to remove justify-content: center; from .card-container class:
const { ref } = Vue const app = Vue.createApp({ setup() { const dummyData = ref([{id: 1, title: 'aaa'}, {id: 2, title: 'bbb'}, {id: 3, title: 'ccc'}, {id: 4, title: 'ddd'}, {id: 5, title: 'eee'}, {id: 6, title: 'fff'}, {id: 7, title: 'ggg'}]); return { dummyData } } }) app.component('child', { template: ` <div> {{ data.title }} </div> `, props: ['data'] }) app.mount('#demo') .container { display: flex; justify-content: center; overflow-y: auto; } |
.card-container { display: flex; flex-wrap: wrap; gap: 10px; max-width: 1216px; }
.card { flex: 0 0 calc(33.33% - 10px); max-width: calc(33.33% - 10px); margin-bottom: 20px; box-sizing: border-box; } <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script> <div id="demo"> <div class="container"> <div class="card-container"> <!--<AddCourseCard />--> <child v-for="(item, index) in dummyData" :key="index" :data="item" class="card" /> </div> </div> </div> |
Suggested blog
>Create a project using Vue.js: Beginners Guide
>Authentication with Vue 3 and Firebase
>Plugins and Presets for Vuejs project
>Create a Vue.js application with CLI Services
>Create a project using Vue.js: Beginners Guide
>Create Vue.js application API