📐

How to Use CSS Flexbox

HTML/CSSBeginner

Create flexible layouts with Flexbox.

Code Example

HTML/CSS
<!DOCTYPE html>
<html>
<head>
<style>
  .container {
    display: flex;
    gap: 10px;
    padding: 20px;
    font-family: sans-serif;
  }
  .box {
    flex: 1;
    padding: 20px;
    border-radius: 8px;
    color: white;
    text-align: center;
    font-weight: bold;
  }
  .box:nth-child(1) { background: #ef4444; }
  .box:nth-child(2) { background: #3b82f6; flex: 2; }
  .box:nth-child(3) { background: #10b981; }
  
  .center-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
    background: #f3f4f6;
    margin: 20px;
    border-radius: 8px;
  }
  .center-content {
    background: #8b5cf6;
    color: white;
    padding: 15px 30px;
    border-radius: 8px;
  }
</style>
</head>
<body>
  <div class="container">
    <div class="box">Flex 1</div>
    <div class="box">Flex 2 (wider)</div>
    <div class="box">Flex 3</div>
  </div>
  <div class="center-box">
    <div class="center-content">Centered!</div>
  </div>
</body>
</html>

Explanation

Flexbox uses display:flex on the container. Control alignment with justify-content, align-items, and flex properties on children.

Related Tutorials