CSS (Cascading Style Sheets) is a powerful tool used to control the presentation and layout of web pages. It allows developers to style HTML elements and create visually appealing websites. One of the properties in CSS that helps control the alignment of grid items is justify-self.
justify-self is a CSS property that is used to align an individual grid item horizontally within its grid cell. It works specifically on the grid items themselves and overrides the justify-items property set on the grid container. This property offers several options for alignment, including start, end, center, stretch, and even left and right.
Let’s explore some examples to better understand how justify-self works:
Example 1: Aligning a Grid Item to the Start
Consider a grid container with two columns and two rows. By default, the grid items will be centered within their respective cells. However, if we want to align a specific item to the start of its cell, we can use the justify-self property.
“`html
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 10px;
}
.grid-item {
background-color: lightblue;
padding: 10px;
justify-self: start;
}
“`
In this example, the first grid item (“Item 1”) will be aligned to the start of its cell, while the second grid item (“Item 2”) will remain centered. This creates a visual distinction between the two items.
Example 2: Aligning a Grid Item to the End
Similarly, we can align a grid item to the end of its cell by using the justify-self property with the value “end”.
“`html
.grid-item {
background-color: lightblue;
padding: 10px;
justify-self: end;
}
“`
In this case, the first grid item (“Item 1”) will be aligned to the end of its cell, while the second grid item (“Item 2”) remains centered.
Example 3: Centering a Grid Item
To center a grid item within its cell, we can use the justify-self property with the value “center”.
“`html
.grid-item {
background-color: lightblue;
padding: 10px;
justify-self: center;
}
“`
In this example, both grid items (“Item 1” and “Item 2”) will be centered within their respective cells.
Example 4: Stretching a Grid Item
By default, grid items will stretch to fill the entire width of their cell. However, we can explicitly set the justify-self property to “stretch” to ensure the item occupies the full width.
“`html
.grid-item {
background-color: lightblue;
padding: 10px;
justify-self: stretch;
}
“`
In this case, both grid items (“Item 1” and “Item 2”) will stretch to fill the entire width of their cells.
Conclusion:
CSS justify-self is a powerful property that allows developers to control the horizontal alignment of grid items within their respective cells. By using values such as start, end, center, and stretch, we can achieve precise control over the positioning of grid items. Understanding and utilizing justify-self effectively can greatly enhance the layout and visual appeal of web pages.