Sunday 4 February 2024

What is display: flex in CSS?


What is display: flex in CSS?

display: flex is a powerful and versatile property in CSS that allows you to create flexible, responsive layouts by arranging elements along one or more axes. It departs from the traditional block-based layout and introduces a more box-like container where child elements are positioned and sized based on various properties.

Key characteristics of display: flex:

  • Flex container: The element with display: flex becomes a flex container that houses its child elements.

  • Flex items: The child elements of the flex container become flex items, which can be manipulated and arranged within the container.

  • Main axis: There's a main axis, horizontal by default, along which flex items are positioned. You can control the direction with flex-direction.

  • Cross axis: A secondary cross axis perpendicular to the main axis also exists, where you can control alignment with align-items and justify-content.

  • Flexibility: Flex items can shrink or grow based on available space and defined properties like flex-grow and flex-basis.

Benefits of using display: flex:

  • Responsive layouts: Easily create layouts that adapt to different screen sizes by controlling how flex items grow, shrink, and wrap.

  • Flexible alignment: Precisely align items along both the main and cross axes using properties like justify-content, align-items, and align-self.

  • Easy spacing: Manage gaps between items using gap or justify-content: space-between/space-around.

  • Modern layout approach: Offers a more intuitive and powerful way to structure layouts compared to traditional methods.

Common use cases for display: flex:

  • Navigation bars

  • Card layouts

  • Product listings

  • Forms

  • Hero sections

  • Responsive image galleries

  • Aligning elements vertically or horizontally

Here's an example of using display: flex to create a navigation bar:


.nav {
  display: flex;
  justify-content: space-between;
  align-items: center;

.nav-link {
  padding: 10px 20px;
  margin-right: 10px;

This code creates a flex container for the navigation bar, horizontally distributes its links with space between them, and vertically aligns them in the center.


  • display: flex introduces new properties and concepts. Explore them to unlock its full potential.

  • Consider using a CSS grid alongside flex for even more complex layouts.

  • Experiment and practice to master this powerful layout technique.

By understanding the core principles and applications of display: flex, you can create modern, responsive, and well-structured web layouts that enhance user experience across various devices and screen sizes.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.