使用flex實現三欄佈局,兩邊固定,中間自適應

王铁柱6發表於2024-11-22
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Three Column Layout with Flexbox</title>
    <style>
        body {
            margin: 0; /* Reset default body margin */
        }
        .container {
            display: flex;
            height: 100vh; /* Example height, adjust as needed */
        }

        .left-column {
            width: 200px; /* Fixed width */
            background-color: #f0f0f0; /* Example styling */
        }

        .center-column {
            flex-grow: 1; /* This makes the center column take up the remaining space */
            background-color: #ffffff; /* Example styling */
        }

        .right-column {
            width: 300px; /* Fixed width */
            background-color: #e0e0e0; /* Example styling */
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left-column">Left Column</div>
        <div class="center-column">Center Column</div>
        <div class="right-column">Right Column</div>
    </div>
</body>
</html>

Explanation:

  1. display: flex; on the container: This enables flexbox layout for the container element, making its children flex items.

  2. width on the side columns: We set fixed widths for the left-column and right-column.

  3. flex-grow: 1; on the center column: This is the key to making the center column expand to fill the available space. flex-grow determines how much a flex item can grow relative to the other flex items. A value of 1 means it will take up all remaining space. If you had multiple elements with flex-grow set, they would distribute the available space proportionally based on their flex-grow values.

Key improvements over other methods (like floats or absolute positioning):

  • Simpler and more intuitive: Flexbox is generally easier to understand and use for this kind of layout.
  • Responsive by default: The center column automatically adjusts its width as the browser window resizes.
  • Handles vertical alignment well: Flexbox provides excellent control over vertical alignment within the container, which can be tricky with floats.

This example provides a basic three-column layout. You can further customize the appearance and behavior with additional flexbox properties and CSS styling. For example, you can use align-items to control vertical alignment, justify-content to control horizontal alignment, and add padding, margins, etc. as needed.

相關文章