Creating customizable Isotope objects using custom CSS margins that are influenced by the child-nth selector and JavaScript

My recent project involved creating a simple .isotope gallery, and when viewing the selected #portfolio-wrap container in Chrome Dev Tools, here is how it appears:


Unfortunately, I am unable to upload three links here. Please visit this link for more information:
--> Gallery - check image 1 <--


Each .isotope object (a circle with text) has the following CSS:

margin: 0 10px 0 10px;

Here is how it looks on the screen:

--> Check image 2 now <--

There are four objects in the row. What I want is no margins for left and right side of first and fourth item so that every one is sticking to "walls" of parent body container. Edit:
Every item should have bottom margin of 20px and every item except 1,5,9 or in other words 4n+1 should also have left-margin of 20px. So they will nicely stack. image

I attempted to achieve this using `nth-child`:

#portfolio-wrap > div:nth-child(4n+1)  {
    margin: 0 0 20px 0;
}

However, this approach caused some bugs in the Isotope layout, as shown below. The red numbers represent consecutive child numbers as per the code without filtering:

--> Check image 3 now <--

While the margin applied correctly to the first and fifth children, there were two persistent issues:

  1. The applied margin did not change after filtering.
  2. An alignment bug was present, as shown in the last Imgur link.

Regarding point 1,
I found a JavaScript solution to address one of the problems, but it only partially worked for me: Stackoverflow - click When applying the 4n+1 code, it does not seem to work. Can someone help find the issue? (I'm not very experienced with JavaScript)

var x = 0;
$('.portfolio-item:not(.isotope-hidden)').each(function(){
     for (x = 4*x+1; x <= 50; x++ ) { 
        $(this).css('margin','0 0 20px 0') 
     } else {
        $(this).css('margin','0 0 20px 20px')
     }
})

As for point 2,
I'm unsure about the cause of the alignment bug. It's not due to excessive margins affecting the wrapper.

Update for everybody:

I managed to fix my JavaScript code, and it now works as intended:

$('.portfolio-item:not(.isotope-hidden)').each(function()) {
        for (x = 1; x <= 50; ++x) { 
        if ((x - 1) % 4 == 0) {
            $(this).css('margin','0 0 20px 0') 
        } else { 
                $(this).css('margin','0 0 20px 20px')  
        } 
    }}

Despite resolving the JavaScript issue, the layout bug persists as seen in image 3!

Additionally, the JavaScript is not applying new margins after filtering... :(

Update 2:

To solve the problem, I incorporated gutterWidth (refer to Isotope manuals). However, applying just the gutterwidth is insufficient; you need to include a lengthy piece of code from the demo showcasing gutterwidth specifications. Isotope documentation could use improvement in this area.

Answer №1

To style every first and fourth child element in a row of 4 elements with specific margins, you can implement the following CSS rules (based on the classes mentioned in your query...)

#portfolio-wrap > div:nth-child(4n+1)  {
    margin-left: 0px;
}
#portfolio-wrap > div:nth-child(4n+4)  {
    margin-right: 0px;
}

Layout Issue

It seems like there is a layout problem in your code. Element #5 may be floating to the right, causing #3 to shift down due to the floating property. Since #1 has a bottom margin of 20px, #3 cannot align to the left of the container. Finally, #4 fits below #3 and aligns with the left side of the container. This behavior is expected according to the Visual formatting model.

Javascript Function

Check your JavaScript function as well. Make sure to include an else statement after an if statement.

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

Unable to transfer content to clipboard from a Popper element nested within a Dialogue component in Material-UI

If you want to see the bug, try opening this link in Firefox. It almost crashed Chrome :P https://codesandbox.io/s/73z5293391 Click on the OPEN SIMPLE DIALOGUE button. A dialogue will appear, then click on the TOGGLE POPPER button. Now a Popper will be d ...

PHP displays the array returned by Ajax as "[object Object],[object Object]"

When working with Jquery, I am creating two arrays - one embedded inside the other. Here is an example of what it looks like: arrayOne = [{name:'a',value:1}, {name:'b',value:2}] var arrayTwo = [{name:'foo',value:'blah&ap ...

Is it possible to verify if each value satisfies a condition within a Javascript function?

I am currently working on a project using Vue.js and Laravel where I have a data list named "questions." My goal is to iterate through this list and check if the answer value for each question is not null. If any question has a null answer, I want to preve ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

Struggling to find a way to showcase API data on a HTML site

Is there a way to dynamically show the live prices of crypto currencies on my website? I wrote a script that successfully displays the current price, but I'm struggling with implementing auto-refresh using setInterval. Here's the code I have so f ...

A guide to modifying the color of the Menu component in material-ui

Currently, I am utilizing the Menu component from material-ui and facing an issue while trying to modify the background color. The problem arises when I attempt to apply a color to the Menu, as it ends up altering the entire page's background once the ...

Is there a way to prevent Chrome from highlighting text that matches the content of a `position: fixed` element?

I currently have a Toc element in my HTML with the property position: fixed. (This means it remains in place as you scroll) My goal is to prevent Chrome's Find Text feature from recognizing text within that Toc element. (Ideally using JavaScript) ...

Unable to locate property 'location' due to being undefined

When trying to use the react-router-dom 4.0.0 library, an error was encountered: Uncaught TypeError: Cannot read property 'location' of undefined The issue seems to be with browserHistory. Previously, I had been using react-router 2.x.x witho ...

Printing in HTML is limited to only one page

While printing an HTML table that can vary in length, I often encounter the issue of it printing multiple pages. Is there a way to limit the printing to just one page through coding? Yes, you can achieve this by using the option in the browser print dialog ...

Show the day of the week

I'm seeking a solution to display the upcoming Friday of each week within Wordpress. We were able to achieve this in the past using the code below on non-Wordpress platforms, but it seems outdated and no longer functional. For example: This week&apos ...

Encountering an issue with the history module when utilizing the webpack dev server

I am encountering an issue while trying to run webpack dev server. The history functionality was working fine until I started using the webpack module. A warning message appeared in my console: WARNING in ./src/history.js 2:15-35 export 'createBrows ...

Django Crispy Forms do not support JavaScript functionality

In my project, I am working on creating a client form where the country, province, and city are selected based on different models: class Country(models.Model): Country = models.CharField(max_length=100, unique=True) def __str__(self): ...

Is it possible to trigger a directive using a function and then access the generated style?

My directive is designed to randomly select a color and assign it to a new user as an avatar. The random color generation and directive functionality are working as expected, but I'm looking to expand the functionality further and need some assistance ...

An effective way to prevent right-clicking on iframes across all websites

I am facing an issue with disabling right click for the iframe. I've successfully disabled it for the default URL of the IFrame, but when displaying any other webpage, the right click remains usable. Below are the sample codes I have used: document.o ...

What steps should be taken to switch a class from one li element to another and remove it in the process?

As I develop the navigation bar for my website, I am faced with a challenge. I want to create a button-like behavior where clicking on an li element triggers a drop-down section underneath it without using the # attribute to prevent jumping to the top of t ...

Combining the powers of Javascript and Drupal can create

My current setup includes an "open video" button and a form that triggers an ajax call to render files with the corresponding buttons when users click on handouts or videos. I have encountered a problem: Whenever I click on "open the video" after renderi ...

Developing an export feature for a mean application

Attempting to develop a basic module for organizing accounts on a website seemed like a straightforward task. I thought it would be as simple as creating a file with some functions, wrapping it in module.exports, and everything would work smoothly. However ...

Firebase Functions: Your functions are missing a definition

I have the following code in index.js: exports.makeUppercase = functions.database.ref('/messages/{pushId}/original').onCreate((snapshot, context) => { // Fetch the current value written to the Realtime Database. const original = snapshot. ...

How can I convert a string number with leading zeros into a string in a node.js environment?

When rendering a page, I pass the id as a string (e.g. 001, 002) but at the client side, I receive it as a number (e.g. 1, 2). res.render('leafletDemo',{id:userID,latitude:latitude,longitude:longitude}); Is there a way to keep the id as a str ...

jquery events such as onSubmit, onComplete, etc. are commonly used

It's interesting to observe that many tools in jQuery, especially those involving ajax, contain hooks like onSubmit, onComplete, and more. Is there a specific term for this practice and the standards associated with it? Does this practice belong sol ...