Engineering Machine
Engineering Machine

Reputation: 642

Align to center image in bootstrap carousel

This is what I have: enter image description here

I want to make each image appear in the centre of the carousel. This is my javascript code I decided to implement:

$('.carousel-inner img').each(function(){
    // image dimensions
    var w = $(this).width();

    //get parent dimensions
    var div_w =$(".carousel-inner").width();

    //set img position
    this.style.left = div_w / 2 - w / 2 + 'px';
});

This code should adjust the left margin for each image according to their width. The problem is that this code will apply the left margin from first image for each image from each slide; instead, it should calculate for each image the margin separately.

Thank you

Upvotes: 0

Views: 436

Answers (1)

guest271314
guest271314

Reputation: 1

An .active class appear to be assigned to parent element of image being displayed

Try

if ($(this).parent("div.item").is(".active")) {
  this.style.left = div_w / 2 - w / 2 + 'px';
}

Upvotes: 1

Related Questions