You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Flexbox实现内容撑满视口?相关CSS及HTML代码问题

Fix & Implement Full Viewport Layout with Flexbox

Let's walk through fixing your code and getting the layout to fill the entire viewport properly.

Step 1: Correct HTML Errors & Complete the Structure

First, fix the typo <hedad> to <head>, then close all unclosed tags and add basic required elements to make the HTML valid:

<html>
  <head>
    <meta charset="UTF-8">
    <title>Full Viewport Flex Layout</title>
    <style>
      /* Adjusted CSS will go here */
    </style>
  </head>
  <body>
    <div class="viewport-container">
      <header>Header</header>
      <div class="row">
        <div class="col col_3">
          <nav>
            <ul>
              <li>One</li>
              <li>Two</li>
              <li>Three</li>
            </ul>
          </nav>
        </div>
        <div class="col">
          <main>main content here...</main>
        </div>
      </div>
    </div>
  </body>
</html>

Step 2: Adjust CSS to Fill the Viewport

To make the content stretch to the full viewport height, we need to ensure root elements and flex containers have the right height settings. Here's the updated CSS, building on your original styles:

/* Reset default margins/paddings to avoid unexpected spacing */
html, body {
  margin: 0;
  padding: 0;
  height: 100%; /* Make root elements take full viewport height */
}

/* Outer container to hold header and main content row */
.viewport-container {
  display: flex;
  flex-direction: column; /* Stack children vertically */
  height: 100%; /* Inherit full height from body */
}

/* Your original styles, plus critical adjustments */
header, nav, main {
  border: 1px solid red;
}

.row {
  display: flex;
  flex: 1; /* Make this row take all remaining space below the header */
  flex-basis: 100%; /* Fallback for older browsers */
}

.col {
  flex-grow: 1;
  flex-shrink: 1;
  flex-basis: 0;
}

.col_3 {
  flex: 0 0 25%; /* Fixed 25% width for the sidebar */
}

Key Details to Note

  • html, body height: 100%: This ensures the root elements span the full height of the viewport, so child containers can inherit this height.
  • .viewport-container flex column: Arranges the header and .row vertically, allowing the row to expand to fill any remaining space.
  • .row flex: 1: Tells this container to take up all available vertical space that the header doesn't use, making the nav and main content stretch to the bottom of the viewport.
  • Original .col/.col_3 styles: Maintain the horizontal flex layout (sidebar takes 25% width, main content takes the rest of the space).

内容的提问来源于stack exchange,提问作者dagda1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:49:46