Q. Explain `display:grid` in css
Answer:
The display: grid property in CSS is used to create a grid container, which is a layout system that allows you to design complex web layouts in a two-dimensional grid. With CSS Grid, you can define rows and columns, and then place elements (grid items) within the defined grid, providing a powerful and flexible way to structure your web page layout.
Here's a breakdown of how display: grid works and its key components:
Grid Container:
The element to which you apply display: grid becomes the grid container.
It can be any block-level or inline-block element, like a div.
.container {
display: grid;
}
Grid Items:
Elements that are direct children of the grid container are the grid items.
These items will be automatically placed within the grid unless you specify otherwise.
.item {
/* Styles for grid items */
}
Grid Rows and Columns:
You define the structure of the grid using the grid-template-rows and grid-template-columns properties.
You can specify the size of rows and columns using various units (e.g., pixels, percentages, fr for fractional units).
.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;
}
Grid Gaps:
You can set the gap between grid items and grid lines using the gap property.
It simplifies spacing within the grid.
.container {
gap: 10px;
}
Placing Items in the Grid:
By default, grid items will flow into the grid in the order they appear in the HTML.
You can explicitly place items in the grid using properties like grid-column and grid-row.
.item {
grid-column: 1 / 3; /* Places the item in columns 1 and 2 */
grid-row: 1; /* Places the item in row 1 */
}
Responsive Layouts:
CSS Grid is responsive by default, making it easy to create layouts that adapt to different screen sizes.
.container {
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
}
For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 50px 50px;
gap: 10px;
}
.item {
border: 1px solid #000;
padding: 10px;
text-align: center;
}
</style>
<title>CSS Grid Example</title>
</head>
<body>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</body>
</html>
No comments:
Post a Comment