简体   繁体   中英

CSS flexbox positioning of child elements

I'm trying to fill the available space of my flexbox layout. The goal is to fill the empty space next to the first project element with project two and three while project four to six are located in a new line.

HTML:

<section class="projects">
  <article>
    Project 1
  </article>
  <article>
    Project 2
  </article>
  <article>
    Project 3
  </article>
  <article>
    Project 4
  </article>
  <article>
    Project 5
  </article>
  <article>
    Project 6
  </article>
</section>

CSS (SCSS):

.projects {
  display: flex;
  flex-flow: row wrap;

  article {
    align-items: center;
    display: flex;
    flex: 0 50%;
    height: 10rem;
    justify-content: center; 

    &:nth-child(1) {
      background-color: #c00;
      height: 20rem;
    }

    &:nth-child(2) {
      background-color: #0c0;
    }

    &:nth-child(3) {
      background-color: #00c;
    }

    &:nth-child(4) {
      background-color: #cc0;
      flex: 1 30%;
      order: 5;
    }

    &:nth-child(5) {
      background-color: #c0c;
      flex: 1 auto;
    }

    &:nth-child(6) {
      background-color: #0cc;
      flex: 1 auto;
      order: 6;
    }
  }
}

I created a codepen example about this. What I want to get is shown in this image .

What am I missing to solve this problem?

One (tricky) posibility is to play with margins

I have added a negative margin to the first element, to allow it to overflow.

Now there are 3 rows, and the 3rd element is starting the 2nd row.

And I have added a left margin to it, to force it under the second element

 .projects { display: flex; flex-flow: row wrap; } .projects article { align-items: center; display: flex; flex: 0 50%; height: 10rem; justify-content: center; } .projects article:nth-child(1) { background-color: #c00; height: 20rem; margin-bottom: -10rem; /* added */ } .projects article:nth-child(2) { background-color: #0c0; } .projects article:nth-child(3) { background-color: #00c; margin-left: 50%; /* added */ } .projects article:nth-child(4) { background-color: #cc0; flex: 1 30%; order: 5; } .projects article:nth-child(5) { background-color: #c0c; flex: 1 auto; } .projects article:nth-child(6) { background-color: #0cc; flex: 1 auto; order: 6; } 
 <section class="projects"> <article> Project 1 </article> <article> Project 2 </article> <article> Project 3 </article> <article> Project 4 </article> <article> Project 5 </article> <article> Project 6 </article> </section> 

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