I am trying to create grid/layout consists of squares. Four squares in each row. Squares can't distort on screen resize. Width and height must be the same all the time (I don't want fixed values). I must use CSS grid. Can anyone help me ?
.container { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; grid-gap: 5px; } .container div { background-color: red; } <div class="container"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> With CSS Grid Layout, we get a new flexible unit: the Fr unit. Fr is a fractional unit and 1fr is for 1 part of the available space. The following are a few examples of the fr unit at work. The grid items in these examples are placed onto the grid with grid areas.
Repeat() is a notation that you can use with the grid-template-columns and grid-template-rows properties to make your rules more concise and easier to understand when creating a large amount of columns or rows.
With CSS only you could use a pseudoelement to keep always the aspect ratio to 1:1 or use the new aspect-ratio property , e.g.
.container { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; grid-gap: 5px; } .container div { background-color: red; aspect-ratio: 1; } <div class="container"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> For the fun, curiosity of grid behavior and to avoid a pseudo element,
You may also set an height equal to the width of your grid container, the grid system will automaticly stretch the rows.
A good reminder to mind :
https://css-tricks.com/snippets/css/complete-guide-grid/
and examples https://gridbyexample.com/
working example if your grid uses entire browser's width
* { margin: 0; padding: 0; } .container { display: grid; height: calc(50vw - 5px); /*instead playing around with grid gap gap */ grid-template-columns: 1fr 1fr 1fr 1fr; } .container div { /* bg to show i'm squarred or not ? */ background-image: linear-gradient( 45deg, transparent 50%, rgba(0, 0, 0, 0.5) 50%); margin: 0 5px 5px 0; /*instead playing around with grid gap gap */ background-color: red; } /* extra for demo, not needed */ .container { counter-reset: test; } .container div { display: flex; /* or grid */ } .container div:before { counter-increment: test; content: 'Div N°:'counter(test)' -'; margin: auto;/* center me */ color: yellow; <div class="container"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> A codepen to fork or play with
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With