What is the best way to showcase my divs in a masonry layout using flexbox?

I am attempting to design display divs in a masonry style using flex/flexbox. The layout must consist of a maximum of 2 columns, with each div having the same width (thus dividing into 2 columns equally) while varying in height based on their content. Some divs will be shorter than others.

Getting straight to the issue:
https://i.sstatic.net/Jfmqh.png

The blue boxes represent my divs (children) with distinct content in each. You can observe that they share the same width and some have less height than others.

Issue: There is a noticeable gap between the top and bottom child in the left column. The lower child should move up to align with the bottom of the upper child. How can I resolve this?

UPDATE:

Here's the CSS being utilized:

#main {
   width: 100%;
   height: auto;
   display: -webkit-flex; /* Safari */
   display: flex;
   flex-direction: row;
   flex-wrap: wrap;
}

.divBob {
   -webkit-flex: 1;  /* Safari 6.1+ */
   -ms-flex: 1;  /* IE 10 */    
   flex: 0 1 auto;
   padding: 5px;
   border: 1px solid #CCE0FF;
   margin: 5px;
   width: 45%;
   height: 100%;
   background-color: #F0F3FA;//#F9FBFF;
}

.divBob:nth-child(2n+1) {
   clear: right;   
}

Answer №1

Is there a specific requirement for using flexbox in this case?

If you are open to exploring alternative methods, this tutorial provides detailed instructions on how to create masonry-style layouts. You can also see the end result here.

Here is an example of the markup used in the demo:

<div class="masonry">
   <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
   <div class="item">Neque, vitae, fugiat, libero corrupti officiis sint facilis tempora quidem repudiandae praesentium odit similique adipisci aut.</div>
   <div class="item">Incidunt sit unde minima in nostrum?</div>
   <div class="item">Ducimus, voluptates, modi, delectus animi maiores consequuntur repellat quisquam fugiat eum possimus enim culpa totam praesentium magni quae!</div>
   <div class="item">Lorem ipsum dolor sit amet, dicta dolore adipisci hic ipsam velit deleniti possimus cumque accusantium rerum quibusdam.</div>
   <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae, praesentium consequatur ducimus commodi quam ex illo omnis dicta reiciendis vel nesciunt deserunt aut sequi nam mollitia perferendis ipsam possimus temporibus!</div>
   <div class="item">Ab, adipisci, temporibus eaque quis harum perferendis incidunt cupiditate doloribus dolor numquam voluptates ipsum dolore aspernatur et voluptate ipsam beatae animi culpa.</div>
</div>

The layout utilizes CSS properties like column-count and column-gap to control the number of columns:

.masonry { /* Masonry container */
    -moz-column-count: 4;
    -webkit-column-count: 4;
    column-count: 4;
    -moz-column-gap: 1em;
    -webkit-column-gap: 1em;
    column-gap: 1em;
}

This style should be applied to each child element:

.item { 
    display: inline-block;
    margin: 0 0 1em;
    width: 100%;
}

The tutorial also offers a link to a JavaScript fallback for older browsers here.

Following these steps will help you achieve a Masonry-style layout effectively.

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

Issues with PHP Form Email DeliveryIt seems that there is a

I currently have a ready-made form that is constructed using html, css, jquery, and ajax. It's basically copied and pasted onto my contact page for now. This is the code I include before the html tag on the contact.php page. <?php session_name(" ...

Insert metadata tag into the head element of the parent iframe

I am looking to insert a meta tag element into the head element of an Iframe parent. I attempted window.parent.$('head').append('sometext'); This method worked when the source file and iframe file were in the same folder, however it d ...

Enhancing a character's appearance with custom CSS styling

In my code, I want to highlight a single character throughout the page. I want the lines between each word to be a different color from the rest of the text using CSS, without having to add span tags to each one individually. Anti-virus End Point | Dis ...

sequential organization paired with double-column format

Looking for a CSS-only method to arrange an ordered list (ol) into two columns if it exceeds the height of its container. The number of items in the list can vary, and so can the height of the container. When attempting to set li with properties like widt ...

Looking for an effective method to implement CSS styling within a list cell in JavaFX?

As a beginner in JavaFX with limited knowledge of CSS, I struggled to conduct proper research and provide relevant information here. I apologize for any confusion or duplication. I am seeking a solution to apply CSS to JavaFX controls, specifically in a Li ...

Employing Jquery for restricting checkbox selection based on parent HTML elements

UPDATE I am looking to limit checkbox selection in specific sections on the same page. To prevent conflicting inputs from different sections, I believe using the label selector <label data-addon-name="xxx"> as a separator is the best appro ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Is there a way to use PHP in place of the <form> tag in HTML in order to submit a form from a script and remain on

Currently, the code in my form looks like this: <form action="https://www.paypal.com/cgi-bin/webscr" target="_BLANK" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="paypal@ ...

What is the best approach to creating a website for a client who needs to incorporate their own Youtube videos?

Welcome to my first post on this platform! I have a new project where I am creating a website for a client who wants to easily embed their own YouTube links. As a beginner in web development, this is my first paid task and I'm curious about how I can ...

Gather information from HTML elements that are updated with text dynamically via AJAX calls using Scrapy

My goal is to extract information about mobile phones listed on the 'amazon.in' website from the following link: here using scrapy. Below is the code I am using: from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import Lin ...

Is it possible to achieve the same functionality as :first-child by employing :nth-of-type without a selector?

Currently tackling a console warning related to MUI5/emotion (I believe) I have noticed that the pseudo class ":first-child" might pose potential risks during server-side rendering. It may be worth considering replacing it with ":first-of-type". I wonder ...

What is the process for using JQuery to switch the class of an element to 'nested-class'?

Styling with CSS: #logo-container { position: fixed; right:5px; .home-page { /* homepage styling */ } .content-page { /* Modify the $element's class to this class */ margin-top: 78px; } } Using JQuery to change the class of #lo ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

Validating HTML Forms Using PHP

I am experimenting with a basic HTML login form, but I can't seem to get it to function properly. This is all new to me as I am just starting out with PHP programming. Any assistance would be greatly appreciated! <?php $correctPassword = 'ho ...

Exploring the method of extracting multiple checkbox values from an HTML form

While I'm aware that jQuery can be used to retrieve checkbox values when there are multiple checkboxes, the solutions available online don't seem to work for me. This is because my checkbox inputs are embedded within an HTML form, and none of the ...

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Elements that are hidden or not displayed are still able to receive mouse over events

I am in the process of learning how to handle events within svgs and I have encountered a strange issue. Currently, I am working on an infovis project where I create an interface to display various column-graphs. This part is functioning well so far. Ho ...

Set the background image width to 75% of the screen size

I want to use this image as a background for a section on my page. My preference is to have the white part cover only 75% of the screen, stopping before reaching the content in the left grid. Is it possible to achieve this? I attempted the following CSS: ...

Seeking feedback: Creating unique HTML markup using PHP, with the option of adding tag prefixes

After working on a PHP class that enables the creation of custom HTML markup similar to FB Markup or EE tags, I am now contemplating enhancing it further. The current functionality is based on tag prefixes like this: <ctag:pagination per_page="20" tota ...

The event listener function is not functioning properly on images generated by JavaScript

I'm currently working on placing multiple images on a grid in the center of the page and would like to include a function that triggers when each individual image is clicked. The images are dynamically created using JavaScript and inserted into the do ...