CSS Flexbox
CSS Flexbox is a layout model that allows you to design flexible and responsive layouts more easily than traditional methods. It provides a more efficient way to distribute space and align content within a container, regardless of the size of the container or its contents. Flexbox is particularly useful for creating complex layouts, such as navigation bars, sidebars, grids, and card layouts.
Here's a basic overview of how Flexbox works:
Flex Container:
To use Flexbox, you first designate an element as a flex container by applying display: flex or display: inline-flex to it. This turns all its direct children into flexFlex Items:
The direct children of a flex container become flex items, which can be aligned and positioned within the container using various Flexbox properties.Main Axis and Cross Axis:
Flexbox works along two axes: the main axis and the cross axis. By default, the main axis runs horizontally (from left to right), and the cross axis runs vertically (from top to bottom).Flex Container Properties:
- flex-direction: Specifies the direction of the main axis.
- justify-content: Defines how flex items are distributed along the main axis.
- align-items: Defines how flex items are aligned along the cross axis.
- align-content: Defines how lines of flex items are aligned when there is extra space on the cross axis.
Flex Item Properties:
- flex-grow: Specifies how much a flex item should grow relative to the other flex items in the container.
- flex-shrink: Specifies how much a flex item should shrink relative to the other flex items in the container.
- flex-basis: Specifies the initial size of a flex item before any remaining space is distributed.
- flex: Shorthand for flex-grow, flex-shrink, and flex-basis.
Example
<!DOCTYPE html> <html> <head> <style> .flex-container { display: flex; background-color: DodgerBlue; } .flex-container > div { background-color: #f1f1f1; margin: 10px; padding: 20px; font-size: 30px; } </style> </head> <body> <div class="flex-container"> <div>1</div> <div>2</div> <div>3</div> </div> <p>A Flexible Layout must have a parent element with the<em>display</em> property set to <em>flex</em>.</p> <p>Direct child elements(s) of the flexible container automatically becomes flexible items. </body> </html>You can click on above box to edit the code and run again.
Output
1
2
3