Tips for achieving vertical alignment of a Bootstrap 4 Carousel slide while it transitions

I am currently working on building a carousel to showcase testimonials, but I am facing some challenges regarding the vertical alignment of the slides.

My goal is to have the slides centered when they enter the screen, but currently they start at the top and then jump down to a centered alignment after the transition.

Here is the code:

HTML:

<div id="Testimonials" class="text-center bg-dark py-3">
  <div class="container">
    <div id="testimonial_carousel" class="carousel slide" data-ride="carousel">
      <div class="carousel-inner testimonial-carousel-inner d-flex align-items-center" role="listbox">
        <div class="carousel-item testimonial-carousel active">
          <div class="card">
            <div class="card-body"><i class="fa fa-quote-left"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultricies felis sed lectus porta, vitae vulputate turpis viverra. Suspendisse consectetur augue nulla, quis tincidunt nisi condimentum vitae. Cras congue tincidunt massa vel mattis. Quisque congue elit et mattis auctor. Nam dignissim dictum lacus id lacinia. Ut non accumsan nisi. Pellentesque.</div>
            <div class="card-body"><small>Anonymous</small></div>
          </div>
        </div>
        <div class="carousel-item testimonial-carousel">
          <div class="card">
            <div class="card-body"><i class="fa fa-quote-left"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dui leo, interdum eu faucibus nec, ornare volutpat risus. Vestibulum sem nisl, imperdiet sed rutrum et, semper eu justo. Proin porttitor nisl turpis, imperdiet condimentum urna.</div>
            <div class="card-body"><small>Anonymous</small></div>
          </div>
        </div>
        <div class="carousel-item testimonial-carousel">
          <div class="card">
            <div class="card-body"><i class="fa fa-quote-left"></i> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vestibulum gravida libero, eu elementum neque elementum sit amet. Sed ornare lectus non est luctus placerat. Donec et tristique purus. Ut vel ultrices quam. Sed aliquet, lacus sit amet vulputate imperdiet, augue ipsum gravida erat, eget rutrum ante dolor nec tellus. Praesent mattis, urna vel facilisis ullamcorper, velit arcu ultrices eros, et pellentesque nibh mi sit amet leo. Morbi porta metus vel sapien vulputate, quis congue massa tristique. Donec suscipit quis.</div>
            <div class="card-body"><small>Anonymous</small></div>
          </div>
        </div>
      </div>
      <a class="carousel-control-prev-hidden" href="#testimonial_carousel" data-slide="prev">
        <span class="carousel-control-prev-icon"></span>
      </a>
      <a class="carousel-control-next-hidden" href="#testimonial_carousel" data-slide="next">
        <span class="carousel-control-next-icon"></span>
      </a>
    </div>
  </div>
</div>

CSS

.testimonial-carousel-inner {
    height:auto;
}

.carousel-control-next-hidden,.carousel-control-prev-hidden{
    position:absolute;
    top:43.75%;
    height:50px;
    display:-webkit-box;
    display:-ms-flexbox;
    display:flex;
    -webkit-box-align:center;
    -ms-flex-align:center;
    align-items:center;
    -webkit-box-pack:center;
    -ms-flex-pack:center;
    justify-content:center;
    width:50px;
    color:#fff;
    background-color: rgba(111,111,111,0.2);
    text-align:center;
    opacity:.9
}
.carousel-control-next-hidden:hover,.carousel-control-prev-hidden:hover{
    color:#fff;
    background-color: rgba(0, 115, 255, 0.5);
    text-decoration:none;
    outline:0;
    opacity:0.9;
}


.carousel-control-prev-hidden {
    left:3%
}

.carousel-control-next-hidden {
    right:3%
}

.carousel-control-prev-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E") !important;
}

.carousel-control-next-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E") !important;
}

Javascript

$(document).ready(function() {

    $(window).resize(function() {
        standardiseHeight("testimonial-carousel");
    });


    standardiseHeight("testimonial-carousel");

    function standardiseHeight(divName) {

        // Sets a var to hold the height of the tallest slide

        $maxHeight = 0;

        // Resets previous height setting.

        $("."+divName+"-inner").css("height","auto");


        // Iterates through all slides
        $("."+divName).each(function(i, obj) {
            $thisHeight = $(this).outerHeight();

            //Compares height with the max number, sets max to the highest of the two
            if ($thisHeight > $maxHeight){
                $maxHeight = $thisHeight;
            }
        });

        // Sets the height of the container to the tallest slide
        $("."+divName+"-inner").css("height",$maxHeight+"px");
    }
});

Here is a link to a JSFiddle that demonstrates this:

https://jsfiddle.net/yL877nhz/11/

Some of the strategies I tried but failed include:

Setting the height for the testimonial-carousel class instead of testimonial-carousel-inner.

Adding the "d-flex align-items-center" class to the carousel items instead of the container.

Attaching the "card" class to the "carousel-inner" div, which caused more issues with the transition.

Answer №1

I have implemented a flag to prevent the recalculation function from running more than once simultaneously. This flag is triggered on the window load and resize events. Additionally, all slides in the carousel have been set to equal heights.

let isParsing = false,
  carousel = $('#testimonial_carousel'),
  recalculate = function() {
    if (!isParsing) {
      isParsing = true;
      $('.card').height('auto');
      setTimeout(() => {
        let maxHeight = 0;
        $('.carousel-item', carousel).each(function() {
          maxHeight = Math.max(maxHeight, $(this).height())
        })
        $('.card', carousel).each(function() {
          $(this).height(maxHeight);
        })
        carousel.height(maxHeight);
        isParsing = false;
      })
    }
  }
$(window).on('load resize', recalculate);
.testimonial-carousel-inner {
  height: auto;
}
.card {
  justify-content: space-around;
}
div.card-body {
  flex-grow: 0;
}
.card small{
  padding: 15px;
}
#testimonial_carousel {
  transition: height .3s cubic-bezier(.4,0,.2,1);
}
// Other CSS styles...
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> // Links to external CSS files
// Scripts and HTML markup...

If you wish to change the alignment of .card elements, feel free to modify the justify-content property to space-between or center. Don't forget to use a tool like Autoprefixer for prefixing.

For a more complex requirement like animating the carousel height from slide to slide, it might be better to consider using a carousel library such as Slick, rather than trying to customize Bootstrap v4's carousel component extensively. If you need this specific feature, hiring a developer might be a good option.


It's important to ensure that when asking for help, you make it easy for others to assist you and try to frame your questions in a way that they can benefit a wider audience. Avoid overly specific queries that only apply to your exact situation.

  • Make it easy for others to help you
  • Frame your questions in a general way that can benefit a larger audience

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

What is the appropriate URL for invoking an API function in Symfony from a React component within the same application?

I am in the process of developing a web application using Symfony 3.4.* as the backend and React for the frontend. My tech stack also includes React-Router, Babel, Browserify, Webpack, jQuery, and Bootstrap. Within one of my React components, I have a fun ...

Tips for adjusting container wrapping to accommodate smaller window widths in bootstrap 4

Bootstrap 4 is still new to me, and I haven't had much experience working with Bootstrap 3 either. One issue I've encountered is that when I apply the class col-(breakpoint)-(span) to div elements, they don't automatically align in a single ...

Form Validation Using a Separate Function

Currently, I am utilizing the jQuery Validation plugin from http://jqueryvalidation.org/ to validate my forms. By default, the validation process is triggered when the form is submitted. However, I would like to initiate the validation when a specific func ...

Guide to creating a dynamic column layout with minimum height divs

I am facing an issue with the variable height of my div, causing it to position incorrectly. To demonstrate the problem, I have included a code snippet below. Here is the solution I am seeking: https://i.sstatic.net/XMAMr.png Note: Since the div has a ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

Effect on Label in WordPress Contact Form 7 When Input Field is Populated

Currently, I am attempting to achieve the floating label effect on Contact Form 7 and have encountered an issue. Although I have successfully implemented the label effect on input:focus, I am struggling to make it persist once text has been entered and foc ...

Highcharts memory leakage issue arises when working with jQuery version 2.X

After extensive testing on my AngularJS application, I have discovered a memory leak when using Highcharts with the latest version of jQuery (2.1.4). Below are links to two plunkers for comparison: Using jQuery 1.8.2: http://plnkr.co/edit/lQ6n5Eo2wHqt35OV ...

The jQuery function .on('input') does not trigger in IE8 by itself

Encountering a specific issue with IE8. The event isn't firing in IE8, but functions normally in IE9, Firefox, and Chrome. $('#myId').on('input', function () { //perform some action. } If anyone has a workaround for this probl ...

Mastering the Art of Scrolling

Can someone please tell me the name of this specific scrolling technique? I am interested in using something similar for my project. Check out this example site ...

How to make the second div start on a new row when the first div exceeds its space in CSS

I am trying to figure out how to have two divs side by side with equal width. However, if the text in the first div wraps onto a second line, I want the second div to move below the first one and both divs should double in width. Can CSS handle this type o ...

Can HTML and CSS be used to create button text that spans two lines with different fonts?

When working with HTML attribute values, I am facing an issue where I can't get button text to display in two lines with different font sizes. I have attempted using whitespace in CSS for word wrap, but this solution does not solve my problem. I also ...

I'm not sure where to set the timeout for automatically refreshing the page

Trying to implement an auto-refresh feature on my page to fetch the most recent data from a database. I am anticipating that this will display the latest information without requiring any manual action, but unfortunately, new inputted data is not reflect ...

Enhance your website with footer animations using jQuery!

I am implementing a sticky footer on my website to keep the footer at the bottom using CSS. I want the footer to initially be collapsed and expand when the user clicks on a button, swapping the "expand" link with a different container div inside the footer ...

What is the best way to determine which id has been clicked using jQuery?

Can someone help me figure out how to determine which button has been clicked using jQuery? Here is the HTML code I am working with: <div class="row"> <div class="col-md-6"> <div class="well " id="option_a"> </div& ...

What is the best way to split the children of a parent div into four distinct styling regions using the nth-child selector?

Imagine having a square parent container with 100 child elements of equal sizes, as illustrated below. How can you use the :nth-child selector to target and style the children in the top-left, bottom-left, top-right, and bottom-right corners separately? ...

Issue with spacing dropdown choices within primary navigation bar

Struggling with my final project for a class as the semester comes to a close. I've received minimal help from my Professor and hit a roadblock. The main navigation on the side is working correctly, but the dropdown options are stacking on top of each ...

The act of sorting an item in jQuery triggers a reordering of items

I am working with a collection of items that represent different layers within div elements. One of my goals is to ensure that when I rearrange these items, their corresponding div layers are also sorted accordingly. Here is the list of sortable items: & ...

Issue with Bootstrap: unable to align columns vertically

I am currently learning how to use bootstrap, but I am facing a challenge with vertical alignment of columns. Despite trying various methods, I can't seem to get the content to align anywhere other than the top. Even starting from scratch with code fr ...

Javascript generates a mapping of values contained within an array

In my current project, I am developing a feature that allows users to create customizable email templates with placeholder tags for content. These tags are structured like [FirstName] [LastName]. My goal is to brainstorm the most effective method for crea ...

How to troubleshoot WordPress Ajax function not getting form data

I am currently working on a form in my plugin where I need to send data to my AJAX action function using the standard WP Ajax techniques. Here is the basic structure of my form: <form role="form" id="signup_widget_form" method="post" action="#"> ...