I need to get the amount of spacing between elements in my container which has the justify-content: space-between; property.
Is there any way to do it in Javascript/CSS ? I searched but found nothing...
Thanks !
CodePudding user response:
You can get the offsetWidth
of the container and your two elements.
After that just do the maths
var diff = conatiner.offsetWidth - elementA.offsetWidth - elementB.offsetWidth
console.log(diff)
Check the working JSFiddle link here. Try resizing the screen width and you can see the distance between the blocks being changed. and it displays the new distance between the blocks
CodePudding user response:
What I finally did is creating a function to calculate it :
This solution only works if all items in your container have the same size (which was my case)
const calculateSpaceBetween = () => {
let container = document.querySelector("your container");
let containerWidth = container.offsetWidth;
let containerItems = container.children;
let containerItemsWidth = containerItems[0].offsetWidth;
let containerItemCount = containerItems.length;
let spaceBetween = (containerWidth - containerItemsWidth * containerItemCount) / containerItemCount;
return spaceBetween
To make sure it handles responsive, trigger it in an eventListener like so :
window.addEventListener("resize", calculateSpaceBetween);