Indents in tiles with auto width blocks in CSS
Let's say we have a tile with four blocks in a row:
.child {
width: 25%;
}
Let's add horizontal and vertical padding to our blocks in percentages:
.child {
margin-right: 1.5%;
margin-bottom: 1.5%;
}
.child:nth-child(4n) {
margin-right: 0;
}
So far, what we have done will not work correctly, since the total width of the blocks and paddings is greater than 100%. For correct work, we need to bite off some piece from each block to have room for our paddings. Let's calculate these pieces.
In our case, it turns out that there are four blocks, and between them there are three indents - one and a half percent each. To calculate the piece to be subtracted, you need to divide the total indent by the number of blocks:
1.5% * 3 / 4 = 1.125
Then the width of each block will be equal to:
25% - 1.5% * 3 / 4 = 23.875%
The resulting code will be:
.child {
width: 23.875%;
margin-right: 1.5%;
margin-bottom: 1.5%;
}
.child:nth-child(4n) {
margin-right: 0;
}
You don't have to calculate this indent yourself, but can delegate the calculation work to the calc function:
.child {
width: calc(25% - 1.5% * 3 / 4);
margin-right: 1.5%;
margin-bottom: 1.5%;
}
.child:nth-child(4n) {
margin-right: 0;
}
Let the block width also be calculated by the function calc:
.child {
width: calc(100% / 4 - 1.5% * 3 / 4);
margin-right: 1.5%;
margin-bottom: 1.5%;
}
.child:nth-child(4n) {
margin-right: 0;
}
Set the width of the blocks as a percentage so that the tile has three blocks in a row, with a distance of 3% between them.
Set the width of the blocks as a percentage so that the tile has six blocks in a row, with a distance of 0.5% between them.
Set the width of the blocks as a percentage so that the tile has four blocks in a row and the distance between the blocks is 30px.
Set the width of the blocks as a percentage so that the tile has five blocks in a row and the distance between the blocks is 50px.