Is there a way to rearrange a group of divs using flexbox?

I'm currently exploring the world of responsive web development using media queries, and I have a question - is it feasible to shift an element from one div to another without relying on a script?

In the desktop view, the layout should be like this:

      ---------
div1 |         | div2
div3 |  image  | div4
div5 |         | div6
      ---------

which is the desired arrangement.

On mobile screens, I envision the layout as follows:

      ---------
     |         | 
     |  image  |  
     |         |  
      ---------
         div1
         div2
         div3
         div4
         div5
         div6

However, I seem to face difficulties in moving divs beyond their parent divs.

Below is the HTML code:

<!DOCTYPE html>

<html>
    <head>
        <meta charset = "UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Shuffle</title>
    </head>
    <body>
    
    <div class="header">
          <h1>Shuffle</h1>
    </div>    
          <div id="main">
                <div class="leftBox">
                       <div class="boxItem" id="first">
                                  <p>1</p>      
                       </div>
                       <div class="boxItem" id="third">
                                  <p>3</p>      
                       </div>   
                       <div class="boxItem" id="fifth">
                                  <p>5</p>              
                       </div>
                </div>
                <div class="image">
                        <img src="https://images.unsplash.com/photo-1605842581240-a0e2527d200b?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
                </div>
                <div class="rightBox">
                       <div class="boxItem" id="second">
                                  <p>2<p>
                       </div>
                       <div class="boxItem" id="fourth">
                                  <p>4</p>
                       </div>   
                       <div class="boxItem" id="sixth"> 
                                  <p>6</p>      
                       </div>
                </div>
        </div>
    </body>
</html>

The CSS styles are as follows:

> ...
(presented in a more readable format)
...

If achieving this layout with the current CSS structure is not possible, is there an alternative method to accomplish this utilizing just one flexbox?

You can also find this project on CodePen for reference: https://codepen.io/johntarvis/pen/LYRYVmd?editors=1100.

Answer №1

To achieve this layout, you can use the columns property and set it to 2. It may be challenging to do without jQuery, but for the image part, you can set it to absolute positioning and center it.

Below is an example of the code:

.wrapper {
  position: relative;
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  padding: 0;
}

#main {
  position: relative;
}

.column {
  -webkit-columns: 2;
  columns: 2;
  text-align: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  flex-wrap: wrap;
}

.sub_col {
  display: block;
  width: 34%;
  min-height: 100px;
  border: 1px solid red;
  margin: 0 0 1rem;
  position: relative;
  z-index: 15;
}

.image {
  width: 30%;
  margin: 0 auto;
  padding: 0;
  left: 0;
  right: 0;
  top: 50%;
  position: absolute;
  transform: translateY(-50%);
}

.image img {
  max-width: 100%;
}

@media only screen and (max-width:768px) {
  .column {
    -webkit-columns: 1;
    columns: 1;
  }
  .sub_col {
    width: 100%;
  }
  .image {
    top: 0;
    transform: none;
    margin-bottom: 1rem;
    position: relative;
    width: 100%;
  }
}
<div class="wrapper">
  <div id="main">

    <div class="image">
      <img src="https://images.unsplash.com/photo-1605842581240-a0e2527d200b?ixlib=rb-1.2.1&amp;q=85&amp;fm=jpg&amp;crop=entropy&amp;cs=srgb&amp;ixid=eyJhcHBfaWQiOjE0NTg5fQ">
    </div>

    <div class="column">
      <div class="sub_col">1</div>
      <div class="sub_col">2</div>
      <div class="sub_col">3</div>
      <div class="sub_col">4</div>
    </div>

  </div>
</div>

This configuration ensures that your div elements maintain their order when numbered as 1, 2, 3, 4, and so on.

Answer №2

To achieve the desired layout, you can utilize @media queries and flexbox:

#main {
    display: flex;
    width: 100%;
    flex-direction: row;
    height: 300px;
}
#main > div { width: 33%;}
.leftBox, .rightBox {
    height: 100%; text-align: center;
    display: flex;        
    flex-direction: column;
    justify-content: center;
}    
img {max-width: 100%; height: auto;}
@media screen and (max-width: 768px) {
    #main {
        flex-direction: column;  
        height: auto;
    } 
    #main > div { width: 100%;}
    .image {order: -1;}
}
<div class="header">
        <h1>Shuffle</h1>
    </div>
    <div id="main">
        <div class="leftBox">
            <div class="boxItem" id="first">
                <p>1</p>
            </div>
            <div class="boxItem" id="third">
                <p>3</p>
            </div>
            <div class="boxItem" id="fifth">
                <p>5</p>
            </div>
        </div>
        <div class="image">
            <img src="https://images.unsplash.com/photo-1605842581240-a0e2527d200b?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
        </div>
        <div class="rightBox">
            <div class="boxItem" id="second">
                <p>2<p>
            </div>
            <div class="boxItem" id="fourth">
                <p>4</p>
            </div>
            <div class="boxItem" id="sixth">
                <p>6</p>
            </div>
        </div>
    </div>

Further information on ordering elements with flex can be found on MDN

Explore this related discussion on SO: how can I reorder HTML using media queries?

Answer №3

CSS Grid could be the perfect solution for your layout.

By maintaining a logical HTML ordering of 1 - 6, you can utilize CSS to arrange the display without dealing with absolute positioning. The only drawback arises when you have a varying number of rows and require an image to span across all of them. For such cases, refer to this answer:

To style minimally for mobile devices, replace the code within your desktop media query accordingly. Then, adjust the styling as necessary.

#main {
  /*Define Grid*/
  display: grid;
  /*Allocate 3 equal columns*/
  grid-template-columns: 1fr 1fr 1fr;
  /*Partition into 3 equal rows -- Can be excluded*/
  grid-template-rows: 1fr 1fr 1fr;
  /*Specify a named area for the central picture*/
  /*grid-template-areas: ". Pic ." ". Pic ." ". Pic .";*/
}


#main>.image {
  /*Position the image in column 2*/
  grid-column-start: 2;
  /*Position the image in the first row, spanning 3 rows*/
  grid-row: 1 / span 3;
  /*If using a named area, assign it here*/
  /*grid-area: Pic; */
}

/*For illustrative purposes only; refrain from moving this to your media query!*/
.image>img {
  width: 200px;
}

.boxItem {
  text-align: center;
}
<div class="header">
  <h1>Shuffle</h1>
</div>
<div id="main">

  <div class="image">
    <img src="https://images.unsplash.com/photo-1605842581240-a0e2527d200b?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ">
  </div>
  <div class="boxItem"><p>1</p></div>
  <div class="boxItem"><p>2</p></div>
  <div class="boxItem"><p>3</p></div>
  <div class="boxItem"><p>4</p></div>
  <div class="boxItem"><p>5</p></div>
  <div class="boxItem"><p>6</p></div>
</div>

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

HTML visibility property fails to function

Hey everyone, I'm working on creating some transparent divs with the following code: <div id="ShopMenu"> <center><ul class="shopul"> <li style="margin-left:12%" class="shopli"><a href="../inde ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

My draggable item seems stuck in place. Any ideas on how to get it moving again?

I have been trying to implement some code I found on this link. Despite adding all the necessary file links, the code is not functioning as expected. It should be able to move within the bounds of a container, but it's not working properly. var max ...

Disordered block elements

I am having trouble centering a div in my footer. When I try to center it, the div ends up floating on top of the footer instead. Here is the link to the codepen. footer { text-align: center; background-color: grey; position: fixed; bottom: 0; width: 100 ...

Instructions on how to change the color of specific text to red

Issue: While working on my testimonials page, I am facing a problem with displaying an "ADMIN" tag in red color instead of normal stars for one of the responses by an admin. I have tried various solutions like removing the ending p tag and adding quotes to ...

Ever thought about harnessing the power of SassDoc to create detailed documentation for your sass

After experimenting with sassdoc for documenting our sass mixins and functions, I realized that there doesn't seem to be a straightforward way to generate documentation for our sass variables. Specifically, I am looking for a solution that can output ...

Assistance required with extracting information from JSON format on a website

Seeking assistance in displaying the last 10 songs played on a web page using JSON data. The current code is not fetching and showing the requested information from the json file. https://jsfiddle.net/Heropiggy95/6qkv7z3b/ Any help in identifying errors ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...

What is the best way to alter the background of a div when hovering over a button in a separate div?

Looking to change the background of one div when hovering over a button in another div? Hello, I have a task where I need to modify the background color of a specific div when a button below it is hovered over. The setup involves having an image (a tshir ...

Implementing jQuery slideDown effect on a nested table element

I am facing an issue where the nested table does not slide down from the top as intended when a user clicks the "Show" button. Despite setting the animation duration to 500ms with jQuery's slideDown() function, the table instantly appears. I am using ...

jQuery Modal activated only once upon clicking

Recently, I've been experiencing a frustrating issue that's giving me a splitting headache. Despite scouring this forum for answers, my problem persists. Here's the situation: I have a button that triggers modals. Upon first click after refr ...

What is the best way to retrieve the ID of a <tr> or <td> element?

When working with JavaScript, I have created a dynamic table where each row is structured as follows: <td id="user[i]['id']">user[i]['name']</td> Within this structure, I am seeking to extract the value user[i]['id&ap ...

Steps to transfer the content of a label when the onclick event occurs

Seeking advice on how to send the dynamically varying value of a label upon clicking an anchor tag. Can anyone recommend the best approach to passing the label value to a JavaScript function when the anchor is clicked? Here is a sample code snippet: < ...

Retain the chosen values even after submitting the form

Consider the following form: <form method="get" action=""> <select name="name"> <option value="a">a</option> <option value="b">b</option> </select> <select name="location"> <opt ...

Triggering a jQuery event upon clicking a link

Trying to achieve a specific functionality here. Clicking on an image triggers a lightbox, but right-clicking and opening in a new tab should lead to a different page. Instagram has a similar feature that I'm aiming for. Using <a href=""> doesn& ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

Dynamically setting CSS values with jQuery to center an image within a div

I'm trying to center an image in a div according to the width of the image after I scale it to have a height of 250px. For example, if I had an image with dimensions 625x450 and, in my CSS file, set the height of the image to be 250px, then the width ...

Retrieve PHP variable from a PHP CSS file

I'm facing an issue where I am unable to retrieve a PHP variable from a CSS file that is loaded in this manner from my index.php: <link href="css/style.php" rel="stylesheet"> Within the style.php file, the code looks like this: <?php heade ...

Make the Angular Modal scrollable except for when a specific div is being click dragged

I am working on an Ionic app that uses AngularJS. One issue I encountered is with a modal popup that can sometimes extend beyond the visible area. To address this, we applied overflow: hidden to its CSS class. However, there is a specific functionality i ...

Determine the quantity of data entries in a Mysql database table using php

I organized a school voting process with 10 questions, allowing participants to select one teacher for each question from a pool of 80 teachers. Once a participant has voted for all questions, a new entry is inserted into my MySQL table. My MySQL table co ...