Flexbox in CSS

Flexbox in CSS

Flexbox in CSS

Flexbox in CSS is a layout model that provides an easy and efficient way to create flexible and responsive layouts. It allows you to align and distribute space among items in a container even if they have different sizes or dimensions.

To use flexbox, you need to define a container element with display:flex or display:inline-flex property, and then define its child elements as flex items. The flex container can have properties that affect the layout of its items, such as justify-content, align-items, flex-direction, and flex-wrap. The flex items can also have their own properties, such as flex-grow, flex-shrink, and flex-basis.

Here’s an example of how to use flexbox in CSS:

HTML:

				
					<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
  <div class="item">Item 4</div>
</div>

				
			

CSS:

				
					.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.item {
  flex-basis: calc(25% - 10px);
  height: 100px;
  margin-bottom: 20px;
  background-color: #ccc;
}

				
			

In this example, we have a container element with display:flex property, which makes its child elements (the .item elements) become flex items. We set the flex-wrap property to wrap, which allows the items to wrap onto the next line if they don’t fit within the container.

We also set the justify-content property to space-between, which evenly distributes the space between the items in the container. The align-items property is set to center, which vertically centers the items within the container.

For the .item elements, we set the flex-basis property to calc(25% – 10px), which sets the initial size of each item to 25% of the container width minus 10px of margin. We also set a height of 100px and a margin-bottom of 20px to create some spacing between the items, and set a background color of #ccc to make them visible.

When you view this code in a web browser, you will see that the items are arranged in a flexible grid layout, with the container evenly distributing the space between them and wrapping onto the next line as needed.

Join To Get Our Newsletter
Spread the love