Search code examples
cssreactjsflexboxcss-selectorsgrid

How to use CSS to split dynamic components?


how can I use CSS to make this division of photos in a dynamic component?

enter image description here

The first item should always be full and the rest in the area below, if you have 2 or 3 photos, divide the space correctly

I'm trying to do this with grid components, like:

  display: grid;
  grid-template-columns: 2fr 1fr;

and combining with &:first-of-type

But I'm not having success with it

Another example with the same component:

enter image description here

  • I can use styled component to do this

Solution

  • Dynamic example using flexbox, if you don't know the number of elements:

    html,
    body,
    section {
      margin: 0;
      height: 100%;
    }
    
    section {
      display: flex;
      flex-flow: row wrap;
      gap: 1rem;
      margin: 1rem 1rem 4rem;
    }
    
    article {
      flex: 1 1 1px;
      display: grid;
      place-content: center;
      background-color: plum;
    }
    
    article:first-child {
      flex: 100%;
    }
    <section>
      <article>1</article>
      <article>2</article>
      <article>3</article>
    </section>
    <section>
      <article>1</article>
      <article>2</article>
      <article>3</article>
      <article>4</article>
    </section>
    <section>
      <article>1</article>
      <article>2</article>
      <article>3</article>
      <article>4</article>
      <article>5</article>
    </section>

    Here's a simpler example for 3 elements where you can grid-column: span 2 the :first-child:

    html,
    body,
    section {
      margin: 0;
      height: 100%;
    }
    
    section {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 1rem;
    }
    
    article {
      display: grid;
      place-content: center;
      background-color: plum;
    }
    
    article:first-child {
      grid-column: span 2;
    }
    <section>
      <article>1</article>
      <article>2</article>
      <article>3</article>
    </section>

    You can adapt it for 4 elements:

    html,
    body,
    section {
      margin: 0;
      height: 100%;
    }
    
    section {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      gap: 1rem;
    }
    
    article {
      display: grid;
      place-content: center;
      background-color: plum;
    }
    
    article:first-child {
      grid-column: span 3;
    }
    <section>
      <article>1</article>
      <article>2</article>
      <article>3</article>
      <article>4</article>
    </section>