写一个三栏布局,两边固定,中间自适应

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三栏布局</title>
    <style>
        body {
            margin: 0;
        }
        .container {
            display: flex;
            min-height: 100vh; /* 确保容器至少占满屏幕高度 */
        }
        .left, .right {
            width: 200px; /* 侧边栏固定宽度 */
            background-color: #f0f0f0; /* 侧边栏背景颜色 */
        }
        .left {
          order: -1; /* 将左侧栏放在最左边 */
        }

        .center {
            flex: 1; /* 中间内容自适应 */
            background-color: #fff; /* 中间内容背景颜色 */
        }


    </style>
</head>
<body>
    <div class="container">
        <div class="left">左侧边栏</div>
        <div class="center">中间内容</div>
        <div class="right">右侧边栏</div>
    </div>
</body>
</html>

Explanation:

  • display: flex; on the container: This enables flexbox layout for the container, allowing its children to be arranged horizontally.
  • min-height: 100vh; on the container: This ensures the container takes up at least the full height of the viewport, preventing content from overflowing below the footer if the content is short. This is a best practice for layouts.
  • width: 200px; on .left and .right: This sets a fixed width for the left and right sidebars.
  • flex: 1; on .center: This allows the center content to take up the remaining available space. flex: 1 is shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0;. This means the center element will grow to fill available space, shrink if necessary, and have an initial size of zero.
  • order: -1; on .left: This ensures the left sidebar appears before the center content, even though it's declared after it in the HTML. This is important for maintaining correct visual order.
  • Background colors: Different background colors are used to visually distinguish the sections.

This code provides a simple, robust, and widely compatible three-column layout. You can easily adjust the widths and styles to fit your specific needs. For example, you could use media queries to change the layout for different screen sizes.

posted @ 2024-12-10 06:07  王铁柱6  阅读(14)  评论(0)    收藏  举报