Flex items are causing a new row

Is there a way to automatically create a new row for a specific group of flex children each time they appear in the following structure?

<div class="container">
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  
  <div class="landscape">landscape</div>
  <div class="landscape">landscape</div>
  
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  
  <div class="landscape">landscape</div>
  <div class="landscape">landscape</div>
  <div class="landscape">landscape</div>
  
  <div class="portrait">portrait</div>
</div>

CSS:

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.portrait {
  flex: 1;
  background: blue;
  height: 300px;
}

.landscape {
  flex: 2;
  background: red;
  height: 150px;
}

Desired layout:

Portrait Portrait Portrait
Landscape Landscape
Portrait Portrait Portrait Portrait
Landscape Landscape Landscape
Portrait
...pattern continues

I have successfully used a div with a "break" class (flex-basis: 100%;) between groups of items (with JavaScript splitting arrays into subarrays), but I am curious if there is a pure CSS solution. The order of portrait and landscape items may vary.

Answer №1

To organize elements of a specific category, consider placing each one inside a flex div container. An example of how this can be achieved is shown below:

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

.protraits, .landscapes{
    display: flex;
    flex-direction: row;
}

.portrait {
  flex: 1;
  background: blue;
  height: 300px;
}

.landscape {
  flex: 2;
  background: red;
  height: 150px;
}
<div class="container">

    <div class="protraits">
        <div class="portrait">portrait</div>
        <div class="portrait">portrait</div>
        <div class="portrait">portrait</div>
    </div>
  
  
    <div class="landscapes">
        <div class="landscape">landscape</div>
        <div class="landscape">landscape</div>
    </div>

    <div class="protraits">
        <div class="portrait">portrait</div>
        <div class="portrait">portrait</div>
        <div class="portrait">portrait</div>
    </div>

    <div class="landscapes">
        <div class="landscape">landscape</div>
        <div class="landscape">landscape</div>
    </div>

</div>

Answer №2

When working with Flex, it may not always be able to achieve a specific layout on its own. One workaround is to use JavaScript to dynamically insert elements between different classes within your HTML:

window.onload = function() {
  let flexChild = document.querySelectorAll(".container > div");

  for (let i = 0; i < flexChild.length; i++) {
    if (i > 0) {
      let item = flexChild[i].getAttribute("class");
      let prevItem = flexChild[i - 1].getAttribute("class");
      //   console.log(item + " - " + prevItem); // see what it founds
      if (item !== prevItem) {
        let flex = document.querySelector(".container");
        let newLine = document.createElement("hr"); //or any tag that suits your needs
        newLine.setAttribute("class", "brLine"); // add a class to style and eventually hide it
        flex.insertBefore(newLine, flexChild[i]);
      }
    }
  }
}
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  max-width: 100%;
}

.portrait {
  flex: 1;/* ?? */
  background: blue;
  height: 20vh;
  /*width:10vh;*/
  margin: 2px;
}

.landscape {
  flex: 2;/* ?? */
  background: red;
  height: 15vh;
  /*width:30vh;*/
  margin: 2px;
}


/* extra css */

.brLine {
  width: 100%;
  border: none;
  margin: 0;
}
<div class="container">
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>

  <div class="landscape">landscape</div>
  <div class="landscape">landscape</div>

  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>
  <div class="portrait">portrait</div>

  <div class="landscape">landscape</div>
  <div class="landscape">landscape</div>
  <div class="landscape">landscape</div>

  <div class="portrait">portrait</div>
</div>

In order to maintain the ratio of portrait to landscape elements, you may need to consider removing or adjusting the flex:x; rules.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for adding a ::after border to a div

Looking for a way to create a border line separator between the top and bottom sections? I've been struggling with this task, but I have managed to make progress by adding a white line. However, I'm facing an issue where the container's widt ...

Tips for adjusting the height and border of Bootstrap tabs

I'm facing an issue with the modal and nav-tabs I created. There are a couple of problems that need to be addressed. Firstly, the tabs have excessive height and I've tried adjusting it using CSS height property, but it's not working as e ...

What is the process for eliminating the message "Hello Member" on the Woocommerce Checkout page?

I've been struggling to remove a certain area on the checkout page without success. I attempted using this CSS code: .avada-myaccount-user-column .username { display:none; } https://i.stack.imgur.com/okFg9.png https://i.stack.imgur.com/GisRQ.png Cu ...

Upon successful authentication, the WebAuthenticationBroker.authenticateAndContinue function does not activate the app

I'm attempting to implement Facebook, Twitter, and Google login using WebAuthenticationBroker.authenticateAndContinue. The authentication page is displayed successfully, but once the authentication is complete, the activated event is not triggered and ...

What is the best technique to incorporate dark/light mode in Bootstrap 5?

Is it best to introduce themes such as dark and light themes in Bootstrap 5 using CSS/SCSS, JavaScript, or a combination of both? Should we create a separate CSS file like dark.css to overwrite classes? Or should we use JavaScript to switch classes like ...

My confusion is running high when it comes to navigating the mobile version of my website

Creating a navigation bar for my website has been challenging. Whenever I switch to mobile view, the list in my navigation bar shifts 40px to the right side of the screen where there's nothing. Is there any way you can assist me with this issue? ...

Choose the nth item from a group of elements that do not have the same parent node in common

Is it possible to select a specific li element within a dynamic HTML structure without knowing the exact number of ul elements or li elements in each? From my understanding, neither :nth-child nor :nth-of-type can achieve this due to the elements needing ...

Tips for arranging letters on separate lines using CSS

I have a set of four divs that display numbers, and I want to show the corresponding words below each number. Despite trying to use the p tag with white-space: pre; in CSS, I have not been successful: #c { padding-top: 30px; padding-bottom: 30px; } ...

Bootstrap Framework 3 causing horizontal scroll due to header styling

Here is the link you requested: This is the HTML Code: <header id="header-10"> </div><!-- /.header-10-top --> <!-- MAIN NAVIGATION --> <div class="header-10-main"> <div class="container"> ...

What is the best way to select an element using a distinct XPath/CSS selector that combines both ID and Class attributes

Below is the HTML snippet that I am working with: <div id="btnCreditCard" class="paymentBtn bitcoin" style="display: none"> <a class="button button-primary button-override has-icon-right" href="javascript:Biz.GlobalShopping.CheckOut.continueT ...

A guide to setting up a Python CGI web server on a Windows operating system

I am looking to set up a basic Python server on a Windows system to test CGI scripts that will ultimately run on a Unix environment. However, when I access the site, it displays a blank page with no source code visible. I am struggling to identify the issu ...

Configuring the color of the active page link in the navbar using Python Flask

In order to highlight the current page that the user is on, I want the link of the current page to have a different color compared to the other page links. This will help the user easily identify which page they are currently viewing. I am implementing thi ...

Saving Arrays through an Input Form in JavaScript

I am working with an HTML form that looks like the following: <div class="form-group"> <label for="first_name">1st Name</label> <input type="text" id="first_name" placeholder="First Name" class="form-control"/> </div> ...

Personalized HTML ProgressBar featuring indicators

As I explore options for creating a progress bar/timeline with the ability to add markings (white lines shown in the image below) upon clicking a button, I've looked into HTML5 canvas and custom jQuery solutions. I'm curious if anyone has any spe ...

placement of facebook and twitter plugins

I am curious to know if there would be any issue if I were to utilize these two scripts on the same page: <a class="twitter-timeline" width="200" height="440" href="https://twitter.com/smth" data-widget-id="347786415695880192"></a> <script ...

Problem with looping through arrays in JQuery using .each() function

Looking for some help with jQuery and JavaScript, please bear with me if my question seems naive. I am attempting to load images from different folders into corresponding divs to create a gallery. <div id="menu"> <div class="gallery" id="div0"&g ...

The navigation bar does not display the CSS when in the active state

I created a navigation bar in ReactJS and I need the tabs to stay highlighted when clicked, but the styles are not applying correctly. I have double-checked that the stylesheet is linked properly based on the Reactjs file structure. For reference, I used ...

`Troubleshooting Problems with HTML5 Video Playback on Mobile Safari`

I have encountered a unique situation: Currently, I am developing a "kiosk" application in Safari that features two videos. One acts as a screensaver while the other is supplementary. The screensaver video loops perfectly using: (done on body onload="init ...

Is it possible to leverage AngularJS string interpolation ({{}}) within the jQuery HTML function?

I am attempting to implement angularJs string interpolation within the Jquery html function $('#existingScoresForWeek').html("<p>{{1 + 1}}</p>"); Unfortunately, the code above is not displaying the Result as 2 <div data-ng-app=" ...

Is it possible for a complete CSS ".class" to possess the specificity of '!important'? [closed]

It's quite challenging to determine the exact inquiry being made here. This question lacks clarity, precision, completeness, specificity, and is overly general or rhetorical, making it impossible to answer in its current state. To obtain assistance in ...