外层有一个自适应高度的div,里面有两个div,一个高度固定300px,另一个怎么填满剩余的高度?

You can achieve this using a combination of CSS Flexbox or Grid. Here are two solutions:

1. Flexbox Solution:

<div class="outer">
  <div class="fixed-height">Fixed Height (300px)</div>
  <div class="fill-remaining">Fill Remaining</div>
</div>
.outer {
  display: flex;
  flex-direction: column; /* Stack children vertically */
  height: auto; /* Adapt to content height */
}

.fixed-height {
  height: 300px;
  /* Add background color or border for visualization */
  background-color: lightblue;
}

.fill-remaining {
  flex-grow: 1; /* This is the key!  It allows this div to expand to fill the remaining space. */
  /* Add background color or border for visualization */
  background-color: lightcoral;
}

Explanation:

  • display: flex and flex-direction: column make the outer div a flex container and stack its children vertically.
  • height: auto on the outer div allows it to adapt to the combined height of its children.
  • height: 300px sets the fixed height of the first child.
  • flex-grow: 1 on the second child tells it to take up all remaining space within the flex container.

2. Grid Solution:

<div class="outer">
  <div class="fixed-height">Fixed Height (300px)</div>
  <div class="fill-remaining">Fill Remaining</div>
</div>
.outer {
  display: grid;
  grid-template-rows: 300px 1fr; /* Define row heights: 300px for the first, and 1fr (fraction) for the second */
  height: auto; /* Adapt to content height */
}

.fixed-height {
  /* Add background color or border for visualization */
  background-color: lightblue;
}

.fill-remaining {
  /* Add background color or border for visualization */
  background-color: lightcoral;
}

Explanation:

  • display: grid makes the outer div a grid container.
  • grid-template-rows: 300px 1fr defines the row heights. 1fr means "one fraction" and will take up all remaining space.
  • height: auto on the outer div allows it to adapt to the content height.

Both solutions achieve the same result. Flexbox is generally preferred for simple one-dimensional layouts (like this one), while Grid is more powerful for complex two-dimensional layouts. Choose the one that best suits your overall layout needs. I personally recommend the Flexbox solution for its simplicity in this case.

posted @ 2024-11-24 17:33  王铁柱6  阅读(28)  评论(0)    收藏  举报