SmartCodingTips

Flexbox Layout in HTML

Flexbox (Flexible Box Layout) is a powerful layout model in CSS that allows you to create complex layouts with simple and flexible alignment of items inside containers.

Basic Flexbox Example


<style>
  .flex-container {
    display: flex;
    background-color: #f2f2f2;
    padding: 10px;
  }
  .flex-item {
    background-color: #4CAF50;
    color: white;
    padding: 20px;
    margin: 10px;
    text-align: center;
    flex: 1;
  }
</style>

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

Common Flexbox Properties

  • display: flex; – Defines a flex container.
  • flex-direction – Sets direction: row, column, etc.
  • justify-content – Aligns items horizontally (e.g., center, space-between).
  • align-items – Aligns items vertically (e.g., center, stretch).
  • flex-wrap – Allows items to wrap onto multiple lines.
  • flex – Defines how a flex item grows or shrinks.

Responsive Flexbox Layout


<style>
  .responsive-flex {
    display: flex;
    flex-wrap: wrap;
  }
  .responsive-flex .box {
    flex: 1 1 200px;
    margin: 10px;
    background-color: #2196F3;
    color: white;
    padding: 20px;
    text-align: center;
  }
</style>

<div class="responsive-flex">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
  <div class="box">Box 3</div>
  <div class="box">Box 4</div>
</div>