carloabelli
carloabelli

Reputation: 4349

Centering Script Slightly Off Center

I am trying to keep one "slide" in my scrollable div centered at all times. For some reason the script seems to be setting it slightly off center and I cannot figure out why. Here is the code:

http://jsfiddle.net/5cp0unwj/

HTML:

<div id="carousel">
    <div class="slide"><img src="http://placehold.it/300x150"/></div>
    <div class="slide"><img src="http://placehold.it/300x150"/></div>
    <div class="slide"><img src="http://placehold.it/300x150"/></div>
    <div class="slide"><img src="http://placehold.it/300x150"/></div>
    <div class="slide"><img src="http://placehold.it/300x150"/></div>
    <div class="slide"><img src="http://placehold.it/300x150"/></div>
</div>

JavaScript (jQuery):

$(document).ready(function() {
  // setup handlers
  var carouselTimeout = null;
  var scrollStop = function() {
    var carousel = $('#carousel');

    var carouselWidth = carousel.width();
    var slideWidth = carousel.find('.slide:first-child').width();
    var margin = carouselWidth / 20; // assumes margin of 5% on slides
    var snapVal = slideWidth / 2 + margin;

    var offset = carousel.scrollLeft();
    slideNum = Math.round(offset / snapVal / 2);
    var newOffset = slideNum * snapVal * 2;
    carousel.animate({
      scrollLeft: newOffset
    });
  };
  $('#carousel').scroll(function() {
    if (carouselTimeout) {
      clearTimeout(carouselTimeout);
    }
    carouselTimeout = setTimeout(scrollStop, 500);
  });
});

CSS:

#carousel {
  width: 100%;
  height: 150px;
  background-color: rgba(0, 0, 0, 0.3);
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
}

#carousel .slide {
  display: inline-block;
  margin: 0 5%;
}

#carousel .slide:first-child {
  margin: 0 5% 0 calc(50% - 150px);
}

#carousel .slide:last-child {
  margin: 0 calc(50% - 150px) 0 5%;
}

Upvotes: 1

Views: 129

Answers (2)

Michael Lawton
Michael Lawton

Reputation: 1510

The inline-block elements have white-space on either side of them.

There are several methods to remove the space such as setting font-size: 0; on the #carousel element. http://jsfiddle.net/5cp0unwj/3/

Refer to https://css-tricks.com/fighting-the-space-between-inline-block-elements/

A better solution would likely be to use a flexbox http://jsfiddle.net/5cp0unwj/6/

Upvotes: 0

j08691
j08691

Reputation: 207913

Inline elements are sensitive to white space in your code. Removing the white space appears to resolve the issue:

<div id="carousel">
    <div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div><div class="slide"><img src="http://placehold.it/300x150"/></div>
</div>

jsFiddle example

Upvotes: 2

Related Questions