简体   繁体   中英

Make some items twice the height in a flexbox grid

I'm trying to create a simple flexbox grid with two columns, however with the option of declaring one of the children as "featured" making it twice the height of the normal children, so given the following markup:

<div class="container">
    <div class="child featured">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
    <div class="child">6</div>
    <div class="child">7</div>
</div>

You'd end up with something like this (margins/padding/border for illustrative purposes only): 在此输入图像描述

However I can't seem to get it to work, the children all just stack under the featured child rather than fill the available space.

My basic CSS is:

.container {
    display: flex;
    flex-flow: column wrap;
}

.child {
    flex: 1 0 50%;
    height: 50vh;
    max-width: 50%;
}

.child.featured {
    height: 100vh;
}

Any idea what I'm doing wrong, or if there is a better approach to this (without resorting to JavaScript)?

Flexbox doesn't support such grid. But you can do it using floats:

 .child { float: left; height: 50vh; width: 50%; outline: 1px solid red; } .child.featured { height: 100vh; } 
 <div class="container"> <div class="child featured">1</div> <div class="child">2</div> <div class="child">3</div> <div class="child">4</div> <div class="child">5</div> <div class="child">6</div> <div class="child">7</div> </div> 

Any idea what I'm doing wrong, or if there is a better approach to this (without resorting to JavaScript)?

The problem is that flexbox is not designed to create anything more than simple grids. Once you ask for something like a masonry layout (which is what you're after), you'll need hacks and workarounds for flexbox to complete the task.

However, this layout can be achieved easily in CSS Grid:

 .container { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 10px; } .child.featured { grid-row-end: span 2; } /* non-essential decorative styles */ .container { padding: 10px; border: 2px solid gray; background-color: lightgray; height: 50vh; } .child { background-color: deepskyblue; display: flex; align-items: center; justify-content: center; font-size: 1.3em; } 
 <div class="container"> <div class="child featured">1</div> <div class="child">2</div> <div class="child">3</div> <div class="child">4</div> <div class="child">5</div> <div class="child">6</div> <div class="child">7</div> </div> 

jsFiddle demo

For a complete explanation of the problem when using flexbox, and how the Grid functions work, see this post:

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