CSS Flexbox - Align Items
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 Items</h3> <!-- flex container --> <div class="flex-container flex-start"> <!-- 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> <!-- flex container --> <div class="flex-container flex-end"> <!-- 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> <!-- flex container --> <div class="flex-container flex-center"> <!-- 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> </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: 250px; } .flex-start { align-items: flex-start; } .flex-end { align-items: flex-end; } .flex-center { 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; } .flex-item-3 { background: yellow; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
align-items
In CSS, align-items
is a property used in Flexbox layouts to align flex items along the cross-axis
(vertical axis) of the flex container. It specifies the default alignment for all flex items within a flex
container
when there is extra space in the cross-axis. The possible values for align-items
include:
stretch
(default): Flex items are stretched to fill the container.flex-start
: Flex items are aligned to the start of the container's cross-axis.flex-end
: Flex items are aligned to the end of the container's cross-axis.center
: Flex items are aligned to the center of the container's cross-axis.baseline
: Flex items are aligned to their baselines.
Experiment with the Code
- Try adding your own boxes and using different values for
align-items
.
Video and Code References
Questions? Subscribe and ask in the video comments: