Using Flexbox to Create Custom Layouts
One method for creating unique layouts is by utilizing flexbox and adjusting the order
property.
By modifying the order
and flex-basis
values of specific items within a flex container, you can control the positioning of elements.
.container {
display: flex;
flex-wrap: wrap;
text-align: center;
}
div {
flex: 1;
}
div:nth-child(3) {
order: -1;
flex-basis: 100%;
}
div:nth-child(5) {
order: 1;
flex-basis: 100%;
}
<section class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
<div>Item 7</div>
</section>
Another approach involves the use of invisible flex items to balance out the layout. This technique requires adding hidden items with visibility: hidden
.
.container {
display: flex;
flex-wrap: wrap;
text-align: center;
}
div {
flex-basis: 20%;
}
.hidden {
visibility: hidden;
}
<section class="container">
<div class="hidden">hidden</div>
<div class="hidden">hidden</div>
<div>Item 3</div>
<div class="hidden">hidden</div>
<div class="hidden">hidden</div>
<div>Item 1</div>
<div>Item 2</div>
<div>Item 4</div>
<div>Item 6</div>
<div>Item 7</div>
<div class="hidden">hidden</div>
<div class="hidden">hidden</div>
<div>Item 5</div>
<div class="hidden">hidden</div>
<div class="hidden">hidden</div>
</section>
Exploring Layout Options with CSS Grid
For more complex layouts and customization, CSS Grid offers a versatile solution.
One approach is to utilize the ASCII art method with the grid-template-areas
property to define a grid layout.
.container {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: repeat(5, 50px);
grid-gap: 10px;
grid-template-areas: " . . . . ."
" . . three . ."
" one two four six seven"
" . . five . ."
" . . . . ."
}
div:nth-child(1) { grid-area: one; }
div:nth-child(2) { grid-area: two; }
div:nth-child(3) { grid-area: three; }
div:nth-child(4) { grid-area: four; }
div:nth-child(5) { grid-area: five; }
div:nth-child(6) { grid-area: six; }
div:nth-child(7) { grid-area: seven; }
/* Additional styles for container and items */
.container {
width: 75%;
margin: 0 auto;
padding: 10px;
border: 1px solid black;
background-color: lightyellow;
}
div {
background-color: lightgreen;
border: 1px dashed gray;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
<section class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
<div>Item 7</div>
</section>
For a more detailed understanding of these Grid properties and their compatibility, refer to the following resources:
- Troubleshooting grid-template-areas with ASCII art
- Addressing layout issues with Grid areas
- Creating a CSS-only masonry layout with horizontal elements