One of the attractive and powerful capabilities of CSS Grid is the ability to create various and responsive masonry layouts. If you want to display different albums of images or cards on your website, and look for a masonry layout that resembles a brick wall or a magazine layout, CSS Grid can assist you in creating such a layout. This type of layout is known as "masonry" or "Masonry".
The masonry layout allows you to present uneven and differently sized content beautifully and systematically. Usually, it is used in blogs, galleries, and product pages. In this layout, the elements flow naturally, and the empty spaces can be minimized, similar to how bricks are laid in a wall.
CSS Grid is a suitable tool for creating masonry layouts. By leveraging the various features of Grid Layout, such as grid-template-columns and grid-auto-rows, complex and flexible layouts can be built easily. You can even use JavaScript to adjust the layout responsively based on screen size.
For example, below we will create a simple masonry layout using CSS Grid. First, we will define the Grid-related properties. Then, we will arrange different elements in various sections. By using grid-area, we can position each element and create a masonry layout.
By applying this technique, you will be able to make your website pages more dynamic and captivating!
Code Example for Masonry Layout with CSS Grid
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>mini-learn - Masonry Layout with CSS Grid</title>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
grid-auto-rows: 150px;
gap: 10px;
}
.grid-item {
background-color: #EEE;
border: 1px solid #DDD;
padding: 10px;
font-size: 20px;
text-align: center;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
</body>
</html>
Line by Line Code Explanation
<!DOCTYPE html>
This declaration indicates that the document is of the HTML5 type.
<html lang="en">
The root HTML element defines the language as English.
<meta charset="UTF-8">
To set the character encoding to UTF-8.
<style>
To write internal CSS styles within the HTML document.
.grid-container
This class defines the main settings for the grid that will create the masonry layout.
display: grid;
Specifies that the container will be displayed as a grid.
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
This line defines that the columns will be filled automatically and with a minimum width of 150 pixels.
gap: 10px;
The space between each grid item is set to 10 pixels.
.grid-item
Styles applied to each item inside the grid, such as background color and padding.
<div class="grid-item">1</div>
Each item with this class will occupy space in the grid.