Making two adjacent elements behave like a single

2020-02-07 07:28发布

问题:

Is it possible to make two adjacent elements behave like a single element, in a flexbox layout?

Say this is my markup:

<div class="flex-container">
   <div>Flower</div>
   <div>Tree</div>
   <div>Bee</div>
</div>

This is what I want on desktop:

|        |           |
|        |  Flower   |
|  Tree  |___________|
|        |           |
|        |   Bee     |
|        |           |

And on mobile:

| Flower |
|________| 
|        |
|  Tree  |
|________| 
|        |
|  Bee   |

So if I could combine Flower and Bee into a single flex column on desktop, it would be nice.

I could probably use a float but I'm already using a flex grid.

This is a page with variable content, I would want the content to grow vertically, and for a vertical scrollbar to appear on the page, if it goes beyond the viewport.

There is no height set on any of the boxes.

I am already using Flexbox for the grid and would not want to add any wrappers.

回答1:

you can do it with CSS grid layout. using grid-template-columns and media-queries

.container {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(2, 1fr);
}

.container div {
  background: gray;
}

.container div:nth-of-type(2) {
  grid-column: 1;
  grid-row: 1 /3;
}

@media (max-width:768px) {
  .container {
    grid-template-columns: 1fr;
  }
  .container div:nth-of-type(2) {
    grid-row: 2;
  }
}
<div class="container">
  <div>Flower</div>
  <div>Tree</div>
  <div>Bee</div>
</div>