How to combine columns and rows using flexbox

I have tried several divs and sub divs to no avail, I am using combination of HTML, JS to create the divs and CSS to manipulate the flexbox, here is what I have got below, bascially I want to have the page show 4 images per row on the page, then have the title and description below the image.

CSS

.wrap-main {
    display: flex;
    /*flex-wrap: wrap; wrap so does not go passed edge of the screen*/
    flex-direction: column;
    height: 150rem;
    position: absolute;
    align-content: center;
    font-size: 10px;
    margin: 20px auto;
    left: 20%;
}

.wrap-main div { flex: 1; }

    .wrap-main img {
        flex: 1;
        height: 200px;
        flex: 1;
        padding: 20px;
    }

.nested-flex {
    display: inline-flex;
    flex-direction: column;
    flex: 1;
}

.items {
    padding: 20px;
    display: inline-flex;
    flex-direction: column;
}

HTML:

<main>
    <div class="move-down">
        <h4 class="text-center">Most popular | Highest Price | Lowest Price </h4>
    </div>
    <div class="wrap-main">

    </div>
</main>

JS

document.addEventListener("DOMContentLoaded", function (event) {
    // Iterate through each item in the array assets for items
    ITEMS.forEach(myFunction)

    function myFunction(item, index) {
        // add images
        var img = document.createElement("img");
        img.src = ITEMS[index].image;
        document.querySelector(".wrap-main").appendChild(img);
        // add price and item description
        document.querySelector(".wrap-main").innerHTML +=
            "<div class='items'>" +
            ITEMS[index].title + "<br>" + ITEMS[index].price + "</div>";
    }
});


// Create container for item and description to make it a column
// append to the start of the contents of 
$(document).ready(function () {
    $(".items").prepend("<div class='nested-flex'");
    $(".items").append("</div>");
});

You seem to be missing the img code in your HTML…

Can you show the layout you are going for without the JS. Or a live example with full working code.

Do you want each 4 items to have its own row container? How should the items (or rows) adjust to screen size changes?

Here is an example where the items just wrap
https://codepen.io/lasjorg/pen/LYYEbQa

1 Like

Sorry about that kev, it looks like lasjorg has uploaded an array almost identical.

Perfect! just had to make a few adjustments because my header was not mentioned in here and caused it to be pushed off screen, but yeah this is exactly what I was looking for. Wow jQuery makes it so much easier, thanks now I can use this jQuery method in many other things!

There is no jQuery in that code, just plain JS.

Are you talking about insertAdjacentHTML, or the use of template literals to construct the HTML.

Oh right my bad, I was referring to the template literals, thought it might have been because of the use of the dollar sign ${item.image} for instance. I see now it is just for embedded expressions.