I want the div elements on first row (deepskyblue
color) to align exactly below the div elements on second row (deepskyblue
color), please provide me a solution how to align and the concept.
document.addEventListener('DOMContentLoaded', () => {
let arrayOfUrls = '{"https://create-react-app.dev/docs/getting-started":"React Start",
"https://scrimba.com/learn/learnreact/first-react-coc0845dcb1a26cb0769a2fea":"React training",
"https://www.digitalocean.com/community/tutorials":"Digital Ocean Tutorials",
"./page1.html":"NextPage",
"./img/flipcard.html":"Flipcard",
"./subscribe.html":"subscribe",
"./react.html":"React stuff",
"https://www.joshwcomeau.com/react/common-beginner-mistakes/":"React Beginner mistakes",
"./futureuse.2html":"future use",
"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#using_addeventlistener":"event listeners"
}';
const obj = JSON.parse(arrayOfUrls);
for (let key in obj) {
elem = document.createElement('div');
elem.setAttribute('id', obj[key]);
console.log(elem);
elem.innerHTML = `<a href=${key}>${obj[key]}</a>`;
document.querySelector('.my_flexx').append(elem);
}
});
.my_flexx {
display: flex;
background-color: green;
flex-wrap: wrap;
justify-content: space-evenly;
width: 600px;
}
.my_flexx div {
background-color: deepskyblue;
margin: 8px;
padding: 6px;
font-size: 14px;
}
<h1 class="my_flexx"></h1>
2
Answers
If what you are trying to achieve is to always have 5 elements at the first row and 5 elements at the second row, where the width of elements on the top and bottom always have the same width, then you can use CSS Grid instead.
Flex is intended to be used to align along 1 axis / dimension only whereas Grid can be used to align across 2 axis / dimensions.
In the example below, I have used
grid-template-columns
CSS property to make the top and bottom fit to at least themin-width
of the childTo align the first row of
div
elements (withdeepskyblue
background color) exactly below the second row, you can addalign-self: flex-start
property to thediv
elements in the first row. This will align the first row elements to the top of their flex container. Here’s the updated CSS code:In this code, the
nth-child(-n+3)
selector targets the first threediv
elements (which are in the first row) and applies thealign-self: flex-start
property to them. This will align them to the top of their container.Note: You should add the
my_flexx
class to an HTML element like adiv
, not ah1
element as shown in your code.