I have an app component that contains a parent element, which is a css-grid container. Inside the parent, I have a couple of box elements. The layout is set up so that each box is 100px x 100px large, and the number of columns is based on the available window width.
I want to transform the box elements based on their position in the grid. Specifically, I want to translate all box elements that are in the more left columns 200px to the left, and respectively the remaining elements to the right. If the window size changes, this should also update.
Example the numbers represent boxes): In this narrow window, I want boxes 1,2,5,6, to move 200 px to the left, and the other four to the right.
1 2 3 4
5 6 7 8
As window width increases, I want boxes 1, 2, 3, 7, 8 to move 200 px to the left, and the rest to the right.
1 2 3 4 5 6
7 8
Creating the component:
const App = () => {
return(
<div id="parent">
{Array.from({ length: 16 }).map((ele, index) => (
<div key={index} className="box"
style={{
transform: `translateX(200px)` //or -200px
}}>
{index}
</div>
))}
</div>
)
}
Styling:
#parent{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
grid-template-rows: 100px ;
gap: 10px;
}
.box{
height: 100px;
width: 100px;
border: 1px solid #333;
}
I assume that by tracking the inner width of the window, I could calculate which boxes need to go left or right, but I wonder whether there is a better way.
user25987386 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.