CSS Flexbox - Align Self
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <h1>CSS Flexbox</h1> <h3>Align Self</h3> <!-- flex container --> <div class="flex-container"> <!-- flex items --> <div class="box flex-item-1"> <p>Flex Item 1</p> </div> <div class="box flex-item-2"> <p>Flex Item 2</p> </div> <div class="box flex-item-3"> <p>Flex Item 3</p> </div> <div class="box flex-item-4"> <p>Flex Item 4</p> </div> <div class="box flex-item-5"> <p>Flex Item 5</p> </div> </div> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
.flex-container { border: 5px solid blue; display: flex; margin: 10px; height: 500px; align-items: center; } .box { padding: 10px; width: 100px; height: 100px; text-align: center; font-size: 20px; } .flex-item-1 { background: red; } .flex-item-2 { background: green; align-self: flex-start; } .flex-item-3 { background: yellow; align-self: flex-end; } .flex-item-4 { background: purple; } .flex-item-5 { background: orange; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
align-self
In CSS, the align-self
property defines how a flex item aligns itself along the cross-axis of the
flex
container. It overrides the align-items
property of the flex container.
The align-self
property can be used on individual flex items and takes the same values as
align-items
, which are:
flex-start
: aligns the flex item to the start of the cross-axis of the flex container.flex-end
: aligns the flex item to the end of the cross-axis of the flex container.center
: centers the flex item along the cross-axis of the flex container.baseline
: aligns the flex item's baseline with the baseline of its parent.stretch
: stretches the flex item to fill the container along the cross-axis. This is the default value.
By default, all flex items have an align-self
value of stretch, which means that they will stretch
to
fill the available space on the cross-axis. If you want a specific flex item to be aligned differently, you can
use
the align-self
property on that item.
Experiment with the Code
- Try adding your own boxes and using different values for
align-self
.
Video and Code References
Questions? Subscribe and ask in the video comments: