I am trying to fetch image data from Pixabay API where I want to show editor's choice images.
The problem is regarding the layout. I am trying to show 3 or 4 images in each row but the layout is breaking down. I don't want to compromise with the responsiveness.
Ideally, 3 columns should display in each row. The problem is after first 3 column, in the second row, columns are not align properly. In fact, is not even adding dynamically in each row. I tried to add in html and in template literal as well. But nothing worked.
let editorChoice = document.querySelector('.editorchoice')
async function getImg() {
let imgData = await fetch('https://pixabay.com/api/?key=12334&editors_choice')
let imgRaw = await imgData.json()
console.log(imgRaw)
let itemData = imgRaw.hits
itemData.map((item) => {
let imgId = item.id
let imgType = item.type
let imgPreview = item.previewURL
let imgTag = item.tags
editorChoice.innerHTML += `<div class="col-lg-4 card">
<img src="${imgPreview}" class="img-responsive center-block" alt="${imgTag}"
</div>
<p class="text-center">${imgTag}</p>`
})
}
getImg()
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet"/>
<div class="container-fluid bg-3 text-center">
<h3>Editor's Choice</h3><br>
<div class="editorchoice"></div>
</div>
First, you're currently using Tailwind CSS, not Bootstrap. Make sure you use the latest version of Tailwind by replacing the
<link />with:Next, to have them displayed in a grid, use the
.gridand.grid-colsclasses built into Tailwind:To add the images themselves, rather than using
.innerHTML, you should ideally usedocument.createElement()anddocument.appendChild():Here, we're looping over the returned results and creating various elements to have them all show up in a 4-column grid.
Here's a runnable code snippet using Lorem Picsum instead of Pixabay: