Tuesday, 4 February 2025

CSS Flexbox: Mastering the align-self Property for Better Layout Control

The align-self property in CSS Flexbox is used to override the default alignment (or the alignment set by the container) for individual flex items. It allows you to adjust the alignment of a single flex item along the cross-axis, which is perpendicular to the main axis of the flex container.

 

In Flexbox, you have two directions for laying out items.

 

1.   Main Axis: This is the primary direction in which the items are arranged. By default, it's horizontal (left to right).

 

2.   Cross Axis: This is the direction that runs across the main axis. If the main axis is horizontal (left to right), the cross axis is vertical (top to bottom). If the main axis is vertical, then the cross axis is horizontal.

 

How align-self Works?

The align-self property accepts the following values:

 

1.   auto: This is the default value. The item inherits the align-items value of its parent container. If no align-items is set, it defaults to stretch.

2.   flex-start: Aligns the item to the start of the cross-axis (top if the flex direction is row).

3.   flex-end: Aligns the item to the end of the cross-axis (bottom if the flex direction is row).

4.   center: Centers the item along the cross-axis.

5.   baseline: Aligns the item’s baseline with the baseline of other flex items.

6.   stretch: Stretches the item to fill the container along the cross-axis. This is the default alignment for items if align-items is set to stretch.

 

align-self.html 

<!DOCTYPE html>
<html>
<head>
    <style>
        .title{
            background-color: lightgray;
            color: black;
            font-size: 25px;
            margin: 10px;
            width: 330px;
        }

        .container {
            display: flex;
            height: 250px;
            border: 2px solid black;
            padding: 10px;
            margin: 10px;
            width: 300px;
        }

        .item {
            background-color: deepskyblue;
            padding: 10px;
            margin: 10px;
            height: 30px;
            color: white;
            text-align: center;
        }

        .scenario{
            margin-bottom: 40px;
            padding-left: 10px;
            padding-right: 10px;
        }

    </style>
</head>
<body>

    <div class = "scenario">
        <h1 class="title">stretch</h1>
            <div class="container">
            <div class="item" style="align-self: auto;">A</div>
            <div class="item" style="align-self: center;">B</div>
            <div class="item" style="align-self: flex-end;">C</div>
            <div class="item" style="align-self: center;">D</div>
            <div class="item" style="align-self: baseline;">E</div>
        </div>
    </div>

</body>
</html>

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment