简体   繁体   中英

Container height equal to it's overlapping children with dynamic heights

Consider you are a block container with fixed width, height: auto and two elements inside of you. Each element has it's own height based on the number of items inside it. Now, you want your children to be positioned at the top, overlapping each other. But, at the same time you want your height to be equal to the height of the child with the most items.

Do you think you can handle it on your own, without asking that weird JS wizardly-guy to look after you and your children?

Also, your children seems to like dynamically changing the number of items inside of them, so you sadly can't use fixed heights here.

Desired result:

想要的结果

(each item is translated to the left a bit for better view)

Yay, some code!

<div class="container">

  <div class="child">
    <div class="item"></div>
    <!-- ... -->
  </div>

  <div class="child">
    <div class="item"></div>
    <!-- ... -->
  </div>

</div>
.container {
  width: 300px;
}

.menu {
}

.item {
  height: 30px;
}

👨‍💻 JSFiddle with example

Yes, you can do this! If you are a CSS grid .

According to the specs, if you put two elements in the same cell. they will overlap each other and with align-items: start; you can align items by their tops.

<div class="container">

  <div class="child">
    <div class="item"></div>
    <!-- ... -->
  </div>

  <div class="child">
    <div class="item"></div>
    <!-- ... -->
  </div>

</div>
/** Creating a CSS grid with a single cell */
.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
  grid-template-areas: 'cell';
  align-items: start;
}

/** Putting both children in the first cell */
.child {
  grid-area: cell;
}

.item {
  height: 30px;
}

And here's the updated JSFiddle to demonstrate the solution.

CSS grid has a pretty good browser coverage. Make sure to use autoprefixer for IE though.


If you know another/better approach, please add it as well, I'm sure it will be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM