Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS left positioning inaccurate

I'm building a multi-screen jQuery feature which is essentially a slideshow with content on each slide. The slides are positioned inline-block and moved using css's left property. However, the positioning is inaccurate, and causes the slides to graudally shift out of position when moving through them. I've removed the animation in order to show the shift a bit more clearly. See here:

var curr = 0;

$('.next').on('click', function(){
    curr++;
    $('.items').css('left', (curr*-140) + 'px')
})

$('.back').on('click', function(){
    curr--;
    $('.items').css('left', (curr*-140) + 'px')
})

http://jsfiddle.net/S8pdH/1/

Any help would be much appreciated!

like image 818
richhastings Avatar asked Mar 22 '23 03:03

richhastings


2 Answers

You're only moving the items left by the amount of the width of the elements, but you're ignoring the space between the items.

The spacing between the items are 4 pixels wide, and I have changed it in your fiddle here.

Basically, you just have to find the width of the elements and the spacing and move the div left by that amount.

$('.next').on('click', function(){
    var distanceBetweenDivs = ($($(".item")[1]).offset().left - ($($(".item")[0]).offset().left)); //144

    curr++;
    $('.items').css('left', (curr*-distanceBetweenDivs)+ 'px')
})

$('.back').on('click', function(){
    var distanceBetweenDivs = ($($(".item")[1]).offset().left - ($($(".item")[0]).offset().left)); //144

    curr--;
    $('.items').css('left', (curr*-distanceBetweenDivs) + 'px')
})

(Edit: If you always have the same spacing between the .item elements and you want to not use a static position change, you can find the exact difference between them doing as I have shown in this updated JSFiddle.)

like image 179
Loyalar Avatar answered Apr 05 '23 14:04

Loyalar


If there is any space between the div opening and closing tags (slides) in the HTML document and they are positioned inline-block there will be also space between them visible on the webpage.

Solution: remove white-space between tags

<div class="item">
...
</div><div class="item"> <!-- no space between closing and opening tag -->
...
</div>

Another, IMHO less elegant solution is to set font-size: 0 for the parent and then reset it for single item

.items {
    font-size: 0;
}
.items .item {
    font-size: 16px; /* or whatever you want */
}
like image 20
matewka Avatar answered Apr 05 '23 16:04

matewka