Customize Swiper js: How to adjust the Gap Size Between Slides using rem, em, or %?

Is there a way to adjust the spacing between slides in Swiper js using relative units such as 2rem?

The entire page is designed with relative units. All measurements are set in rem, which adjusts based on the viewport size for optimal adaptability.

For instance:

* {
   padding: 0;
   margin: 0;
   box-sizing: border-box;
   outline: none;
   font-size: calc(100vw / 1440 * 8);
}

.swiper-slide {
   display:flex;
   max-width: 33.33%
   align-items: center;
   justify-content: center;
   background-color: green;
   color:white;
   font-size: 4rem; (equivalent to 32px)
   padding: 2rem; (equivalent to 16px)
}

However, I encountered an issue with the space between the slides...

The documentation specifies that for spaceBetween: string | number, only a string value can be assigned via JavaScript. Setting a right margin using CSS does not work and the documentation advises against it.

I tried adjusting both the margin and removing it using nth-child for the first and last slide - but this did not yield the expected results. The gap property on the wrapper also did not work.

Even attempting to reassign it in JavaScript through a variable did not produce the desired outcome.

I am seeking assistance. Here is the sandbox - https://codepen.io/divside/full/eYPKNxN The objective is to maintain a consistent distance of 2rem between slides

Any ideas... whether it's gap/margin/padding/ rem in JS or variables... all suggestions are welcome.

Answer №1

Unfortunately, the spaceBetween property is only in pixels and cannot be set in rem.

One workaround could be to define a global constant in your JavaScript file that represents how many pixels one rem is equivalent to, then use that constant as a modifier in your code.

For example:

const rem = 16; // 1rem equals 16px

// continue with your code

spaceBetween: rem * 2,

// add more code

Check out the modified pen here: https://codepen.io/Crist-bal-D-az-lvarez/pen/abRKdyP

For more information, refer to the swiper documentation on spaceBetween:

An updated version of the pen that dynamically updates the value on window resize can be found here: https://codepen.io/Crist-bal-D-az-lvarez/pen/rNqKGWg

Answer №2

illustration one can assign margin: 0 1.2rem to the slide components and set margin: 0 -2.4rem for the swiper-wrapper element this configuration will ensure proper functioning

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

Configuring the default value for a selection menu in Vue3

Obtaining all available categories: const fetchCategories = async () => { let response = await axios.get(`/api/get_all_category/`) categories.value = response.data.categories } The structure of categories.value is shown here: https://i.sstatic.net ...

Executing a JavaScript function from the form attribute value in HTML: Steps to follow

<html> <head> <script type="text/javascript"> function add() { num1 = 20; num2 = 30; total = num1 + num2; return total; } </script> & ...

What is the best way to access a reference to the xgrid component in @material-ui?

Is there a way to obtain a global reference to the xgrid component in order to interact with it from other parts of the page? The current code snippet only returns a reference tied to the html div tag it is used in, and does not allow access to the compo ...

How come my image is not aligned to the right of the header in my HTML code?

My attempt to align an image to the right side of my heading using code was unsuccessful. Here is the HTML snippet I used: /* Aligning with CSS */ #colorlib-logo img { display: flex; align-items: center; width: 30px; height: 30px; } #colorli ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

The utilization of ES Modules within a Next.js server.js

After reviewing a few examples in the Next.js repository, I came across: https://github.com/zeit/next.js/tree/master/examples/custom-server-express https://github.com/zeit/next.js/tree/master/examples/custom-server-koa I observed that these examples ut ...

What is the best way to ensure elements are rendered in Vue only when they are fully prepared?

Is there a way to delay the rendering of images in my list until all content is ready? I want everything, including text and classes, to finish loading before displaying anything. Even with v-cloak, it's not working! I'm having difficulty with t ...

What are some methods to turn off AJAX caching in JavaScript without relying on jQuery?

I'm running into an issue where my current method of framing the ajax url seems to be caching the old response on the second call. How can I ensure that I always get the latest response? Let me know if you need more information. Snippet of Code : va ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

Using React with Axios to trigger several requests with a single action

Let's say a user selects a team from a dropdown menu, triggering a request to an API endpoint. const selectHomeTeamStat = evt => { const { value } = evt.target; getStats(leagueId, value, 'home'); }; In this hypothetical scen ...

Enhanced Vertical Space Produced on my Website in Firefox

For some reason, Firefox is adding an extra 250px at the end of my website below the footer. I have not been able to determine why this is occurring. Note: The site functions properly on all other browsers; the issue is specific to Firefox. You can view ...

Refresh DataTable while making a fetch request

Here is the HTML code snippet where I want to apply DataTable: <div id="reportrange" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc;"> <span></span> </div> <table id=" ...

How can I place the current date inside a red dashed box with text using JavaScript?

Let's Solve This: The date currently appears in the top left corner without any special formatting. My goal is to make it bold, red, and encased in a dashed-red border. I have identified the element by its ID "datetext", corresponding to a "p" tag w ...

My code in NodeJS is not executing in the expected order due to its asynchronous nature

handleRegistration: function (user, req, res, next) { console.log('handleRegistration activated'); user.getData(function(err, info) { if (err) { console.log(err.toString, "error message"); return next(err); } e ...

Triggering jQuery Submit Form when Form is Modified

I need help with automatically submitting a form using jQuery when an input changes. The specific input I am working with is a date picker, and I want the form to be submitted as soon as a user makes a selection. <form id="select_date" name="select_da ...

Trouble with Hero Unit Styles not being implemented

Looking to convert a PSD design to HTML using Bootstrap, but the hero unit is not displaying its default style as expected. <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Errored Out: No content found in file_get_contents('php://input') following an ajax post

I've run into a dilemma and am seeking help. I recently encountered an issue where data sent to a PHP file through an AJAX function seemed to vanish when attempting to retrieve it in the PHP file. Strangely enough, a similar function I implemented yes ...

Next.js: Generating static sites only at runtime due to getStaticProps having no data during the build phase, skipping build time generation

I am looking to customize the application for individual customers, with a separate database for each customer (potentially on-premise). This means that I do not have access to any data during the build phase, such as in a CI/CD process, which I could use ...

Using Angular's $q service in the run block

I have a scenario where I need to load data from local files using the global loadJSON function (though it's not mandatory, it's recommended). Once the data is loaded from all the documents, I want to print the string 'i ve loaded'. T ...

I did not anticipate the React setState function to behave in the manner it did

While working on form validation for my page, I came across a tutorial showcasing a validation method that seems to be functioning correctly. However, there is one aspect that I am struggling to grasp. The tutorial suggests declaring a variable before the ...