James Wong
James Wong

Reputation: 355

How to render the item horizontally (Masonry Layout )?

I would like to render the items horizontally while the page load, refer to following images

<section
        tabindex="-1"
        class="relative mx-8 mt-10 mb-20 max-w-7xl focus:outline-none sm:mx-16 md:mx-20 lg:mx-24 xl:mx-auto"
    >
        <ul
            class="h-full w-full list-none columns-1 gap-4 space-y-12 overflow-hidden pb-32 md:columns-2 lg:columns-3 lg:gap-8 xl:columns-4"
        >
            <ExploreCard
                v-for="(post, index) in posts.data"
                :key="index"
                :post="post"
                :canLike="this.canLike"
            />
        </ul>       
</section>

Currently

enter image description here

Expected

enter image description here

Something like this,
https://reactjsexample.com/rendering-columns-from-a-list-of-children-with-horizontal-ordering/

I am looking for a Js, Vue, or CSS solution.

Upvotes: 4

Views: 2168

Answers (3)

James Wong
James Wong

Reputation: 355

This is an answer with pure CSS from @haltersweb

https://stackoverflow.com/a/37063940/17737657

CSS-only masonry layout

display: inline-block

ul {
    margin-left: .25em;
    padding-left: 0;
    list-style: none;
}
li {
    margin-left: 0;
    padding-left: 0;
    display: inline-block;
    width: 30%;
    vertical-align: top;
}

<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>item 6</li>
  <li>item 7</li>
  <li>item 8</li>
  <li>item 9</li>
</ul>

enter image description here

display: flex

ul {
    margin-left: .25em;
    padding-left: 0;
    list-style: none;
    display: flex;
    flex-wrap: wrap;
}
li {
    margin-left: 0;
    padding-left: 0;
    width: 33.3%;
}

<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>item 6</li>
  <li>item 7</li>
  <li>item 8</li>
  <li>item 9</li>
</ul>

enter image description here

Upvotes: 0

iammtander
iammtander

Reputation: 330

I would advise that you use tailwind class utility of grid to create a grid container: https://tailwindcss.com/docs/display#:~:text=Use%20grid%20to%20create%20a%20grid%20container.

enter image description here

Upvotes: 1

James Wong
James Wong

Reputation: 355

I end up with a package solution and it works perfectly fine!

DaPotatoMan/vue-next-masonry

and this is how it looks like

<masonry
            :cols="{ default: 4, 1024: 3, 768: 2, 640: 1 }"
            :gutter="{ default: 40, 1024: 30, 768: 20 }"
        >
            <div v-for="(post, index) in posts.data" :key="index" class="mb-10">
                <ExploreCard
                    v-for="(post, index) in posts.data"
                    :key="index"
                    :post="post"
                    :canLike="this.canLike"
                />
            </div>
</masonry>

In this way, all the post is rendered in horizontal order !

Upvotes: 1

Related Questions