Creating a Responsive News Card Slider with HTML, CSS, JavaScript, and Swiper

Faraz

By Faraz -

Learn how to make a responsive news card slider using HTML, CSS, and JavaScript. Enhance user experience with an interactive Swiper slider.


Creating a Responsive News Card Slider with HTML, CSS, JavaScript, and Swiper.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

In today's digital age, user experience and visual appeal play a crucial role in web development. One way to enhance both is by creating a responsive news card slider. In this blog post, we will walk you through the entire process, from setting up the HTML structure to adding JavaScript functionality and integrating the Swiper library. Let's get started!

Getting Started

To begin, ensure you have a basic understanding of HTML, CSS, and JavaScript. You'll also need the Swiper library, which is readily available for download and use in your web projects.

Source Code

Step 1 (HTML Code):

A well-structured HTML layout is the foundation of your news card slider. Create a container for your slider and individual cards within it. Use div elements to define each card and its content.

Let's break down the code step by step:

1. <!DOCTYPE html>: This declaration specifies the document type and version of HTML being used, which is HTML5 in this case.

2. <html lang="en">: This is the opening tag for the HTML document. The lang attribute is set to "en," indicating that the page is written in English.

3. <head>: This is the head section of the HTML document, where you typically include metadata and external resources for the webpage.

  • <meta charset="UTF-8">: This meta tag specifies the character encoding for the document, which is UTF-8, a widely used character encoding for text.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is used to instruct Internet Explorer to use the latest rendering engine available.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is used to control the viewport settings, ensuring the page adapts to different device widths and sets the initial zoom scale to 1.0.
  • <title>Responsive News Card Slider</title>: This sets the title of the webpage, which appears in the browser's title bar or tab.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.3.5/css/swiper.min.css">: This line links an external CSS stylesheet (Swiper) for styling the webpage.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">: This line links another external CSS stylesheet (Normalize) that helps standardize default styles across different browsers.
  • <link rel="stylesheet" href="styles.css">: This line links a local CSS stylesheet (styles.css) for additional styling.

4. <body>: This is the body section of the HTML document, where the visible content of the webpage is defined.

  • Inside the <body>, there's a container with the class "wrapper," which holds the main content of the webpage.
  • Within the "wrapper," there's a "background" div containing an image. This is probably the background image for the slider.
  • The "news-slider" section appears to be the main content of the webpage. It contains a series of news card items displayed as a slider.
  • Each news card is defined inside a "swiper-slide" div within the "news-slider__wrp" container. These cards include information like the date, title, text, and image.
  • At the bottom of the news slider, there are navigation controls, including left and right arrows for sliding through the news and a pagination element.
  • Just before the closing </body> tag, there's an SVG element that defines two arrow icons (for left and right) that are used in the navigation controls.
  • Finally, there are script tags that include references to external JavaScript files and a local script ("script.js") for adding interactivity and functionality to the webpage.

Step 2 (CSS Code):

Apply CSS styles to your HTML elements to make the news card slider visually appealing. Design the layout, fonts, colors, and transitions to suit your website's aesthetics.

Let me break down what each section of the code is doing:

1. @import url("https://fonts.googleapis.com/css?family=Quicksand:400,500,700&subset=latin-ext"); This line imports a font named "Quicksand" from Google Fonts. It includes different font weights (400, 500, 700) and specifies that it supports the Latin extended character set.

2. html { position: relative; overflow-x: hidden !important; }: This block sets the CSS for the HTML element. It makes the HTML element have a relative position and hides horizontal overflow (content that goes beyond the screen's width).

3. body { font-family: "Quicksand", sans-serif; }: This block sets the font family for the body of the document to "Quicksand," and if that's not available, it falls back to a generic sans-serif font.

4. a, a:hover { text-decoration: none; }: This code removes the underline decoration from hyperlinks (a elements) and also removes the underline when the link is hovered over.

5. .icon { display: inline-block; width: 1em; height: 1em; stroke-width: 0; stroke: currentColor; fill: currentColor; }: This seems to be defining a class for icons. It sets the display to inline-block, makes the icon a square with a 1em width and height, and specifies that it should use the current text color for both the stroke and fill properties.

6. .background { /* ... }: This appears to define styles for an element with the class "background." It sets its position to fixed, covering the entire viewport, and adds a linear gradient background.

7. .background img { /* ... }: This defines styles for images within elements with the "background" class. It makes the images cover their containers and applies some styling for pointer events and user-select properties.

8. .item-bg { /* ... }: This block seems to define styles for elements with the class "item-bg." These elements have fixed dimensions, a background color, rounded corners, a box shadow, and some opacity and transition effects.

9. .news-slider { /* ... }: This sets styles for a "news-slider" element, specifying a maximum width, margins, and responsive styles for different screen widths.

10. .news-slider__item { /* ... }: Styles for elements with the class "news-slider__item." This includes setting their width, opacity, and pointer events.

11. .news__item { /* ... }: This block appears to style elements with the class "news__item." It sets padding, text color, border radius, and adds transitions for hover effects.

12. .news-date { /* ... }: This block styles elements with the class "news-date," defining padding, margin, border, opacity, and some responsive styles.

13. .news-date__title { /* ... }: Styles for elements with the class "news-date__title," setting font size, margin, and font weight.

14. .news__title { /* ... }: Styles for elements with the class "news__title," specifying font size, font weight, and opacity with some hover effects.

15. .news__txt { /* ... }: Styles for elements with the class "news__txt," setting margin, line height, font size, and opacity with hover effects.

16. .news__img { /* ... }: Styles for elements with the class "news__img," specifying border radius, box shadow, dimensions, and some transition properties.

17. .news__img img { /* ... }: Styles for images within elements with the class "news__img," setting max width and height while maintaining a rounded border.

@import url("https://fonts.googleapis.com/css?family=Quicksand:400,500,700&subset=latin-ext");
html {
  position: relative;
  overflow-x: hidden !important;
}

body {
  font-family: "Quicksand", sans-serif;
}

a, a:hover {
  text-decoration: none;
}

.icon {
  display: inline-block;
  width: 1em;
  height: 1em;
  stroke-width: 0;
  stroke: currentColor;
  fill: currentColor;
}

.background {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.background:after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(45deg, rgba(209, 0, 42, 0.6) 0%, #0E5DC4 100%);
  opacity: 0.9;
}
.background img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  pointer-events: none;
  user-select: none;
}

.item-bg {
  width: 300px;
  height: 500px;
  position: absolute;
  top: 30px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 6px 26px 6px rgba(0, 0, 0, 0.25);
  opacity: 0;
  transition: all 0.3s;
  left: -30px;
}
.item-bg.active {
  left: 0;
  top: 0;
  opacity: 1;
}

.news-slider {
  z-index: 2;
  max-width: 1300px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 60px;
}
@media screen and (max-width: 1300px) {
  .news-slider {
    max-width: 1000px;
  }
}
@media screen and (max-width: 576px) {
  .news-slider {
    margin-top: 45px;
  }
}
.news-slider__wrp {
  display: flex;
  align-items: flex-start;
  position: relative;
  z-index: 2;
}
.news-slider__item {
  width: 400px;
  flex-shrink: 0;
}
@media screen and (max-width: 992px) {
  .news-slider__item {
    width: 340px;
  }
}
.news-slider__item.swiper-slide {
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s;
}
.news-slider__item.swiper-slide-active, .news-slider__item.swiper-slide-prev, .news-slider__item.swiper-slide-next {
  opacity: 1;
  pointer-events: auto;
}
.news-slider__ctr {
  position: relative;
  z-index: 12;
}
.news-slider__arrow {
  background: #fff;
  border: none;
  display: inline-flex;
  width: 50px;
  height: 50px;
  justify-content: center;
  align-items: center;
  box-shadow: 0 6px 26px 6px rgba(0, 0, 0, 0.25);
  border-radius: 50%;
  position: absolute;
  top: 50%;
  z-index: 12;
  cursor: pointer;
  outline: none !important;
}
.news-slider__arrow:focus {
  outline: none !important;
}
.news-slider__arrow .icon-font {
  display: inline-flex;
}
.news-slider__arrow.news-slider-prev {
  left: 15px;
  transform: translateY(-50%);
}
.news-slider__arrow.news-slider-next {
  right: 15px;
  transform: translateY(-50%);
}
.news-slider__pagination {
  text-align: center;
  margin-top: 50px;
}
.news-slider__pagination .swiper-pagination-bullet {
  width: 13px;
  height: 10px;
  display: inline-block;
  background: #fff;
  opacity: 0.2;
  margin: 0 5px;
  border-radius: 20px;
  transition: opacity 0.5s, background-color 0.5s, width 0.5s;
  transition-delay: 0.5s, 0.5s, 0s;
}
.news-slider__pagination .swiper-pagination-bullet-active {
  opacity: 1;
  background: #ffffff;
  width: 100px;
  transition-delay: 0s;
}
@media screen and (max-width: 576px) {
  .news-slider__pagination .swiper-pagination-bullet-active {
    width: 70px;
  }
}
.news__item {
  padding: 40px;
  color: #fff;
  border-radius: 10px;
  display: block;
  transition: all 0.3s;
}
@media screen and (min-width: 800px) {
  .news__item:hover {
    color: #222222;
    transition-delay: 0.1s;
  }
  .news__item:hover .news-date, .news__item:hover .news__title, .news__item:hover .news__txt {
    opacity: 1;
    transition-delay: 0.1s;
  }
  .news__item:hover .news__img {
    box-shadow: none;
  }
}
.news__item.active {
  color: #222222;
}
.news__item.active .news-date, .news__item.active .news__title, .news__item.active .news__txt {
  opacity: 1;
}
.news__item.active .news__img {
  box-shadow: none;
}
@media screen and (max-width: 992px) {
  .news__item {
    padding: 30px;
  }
}
@media screen and (max-width: 576px) {
  .news__item {
    padding: 20px;
  }
}
.news-date {
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 2px solid;
  display: inline-block;
  opacity: 0.7;
  transition: opacity 0.3s;
}
@media screen and (max-width: 576px) {
  .news-date {
    margin-bottom: 10px;
    display: inline-flex;
    align-items: center;
    padding-bottom: 0;
  }
}
.news-date__title {
  display: block;
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: 500;
}
@media screen and (max-width: 576px) {
  .news-date__title {
    margin-right: 10px;
  }
}
.news-date__txt {
  font-size: 16px;
}
.news__title {
  font-size: 25px;
  font-weight: 500;
  opacity: 0.7;
  margin-top: 10px;
  margin-bottom: 15px;
  transition: opacity 0.3s;
}
@media screen and (max-width: 576px) {
  .news__title {
    font-size: 22px;
    margin-bottom: 10px;
  }
}
.news__txt {
  margin: 10px 0;
  line-height: 1.6em;
  font-size: 15px;
  opacity: 0.7;
  transition: opacity 0.3s;
}
.news__img {
  border-radius: 10px;
  box-shadow: 0 6px 26px 6px rgba(0, 0, 0, 0.25);
  height: 200px;
  margin-top: 30px;
  width: 100%;
  transition: all 0.3s;
  transform-origin: 0% 0%;
}
@media screen and (max-width: 576px) {
  .news__img {
    height: 180px;
    margin-top: 20px;
  }
}
.news__img img {
  max-width: 100%;
  border-radius: 10px;
  height: 100%;
  width: 100%;
} 

Step 3 (JavaScript Code):

Implement JavaScript to make your news card slider interactive. You'll need event listeners and functions to control the slider's behavior.

The Swiper library simplifies the creation of sliders. Incorporate it into your project by linking to the necessary CSS and JavaScript files.

Here's an explanation of the code:

1. The code starts by selecting some DOM elements and defining a logging function:

  • It selects an element with the class "item-bg" and assigns it to the variable bg.
  • It selects all elements with the class "news__item" and assigns them to the items variable. Note that there is a redundant selection of a single item with the same class and assigns it to the item variable, but this is not used in the code.
  • It defines a function cLog(content) which logs the given content to the console.

2. There is an if statement checking if the window width is greater than 800 pixels. If the condition is true, it attaches a "mouseover" event handler to elements with the class "news__item."

  • Within this event handler, it further selects all elements with the class "news__item" and iterates over them.
  • For each element, it attaches two event listeners:
  • One for "mouseover," which changes the appearance of the page by making an element with the class "item-bg" active, adjusting its dimensions and position.
  • Another for "mouseleave," which removes the "active" class from the "item-bg" and all elements with the class "news__item."

3. It then creates a Swiper instance for a slider with the class "news-slider." This slider has various configuration options, such as the coverflow effect, loop, keyboard navigation, and more. It also specifies some event handlers to handle the initialization, touch end, slide change, and transition end.

  • On initialization (init event), it selects the active item in the slider, sets it to "active," and adjusts the "item-bg" dimensions and position based on the active item's dimensions and position.
  • On "touchEnd" event, it removes the "active" class from all elements with the class "news__item" and sets the "active" class for the news item within the currently active slide.
  • On "slideChange" event, it removes the "active" class from all elements with the class "news__item."
  • On "slideChangeTransitionEnd" event, it behaves similarly to the initialization event, adjusting the "item-bg" based on the dimensions and position of the active item in the currently active slide.
var bg = document.querySelector('.item-bg');
var items = document.querySelectorAll('.news__item');
var item = document.querySelector('.news__item');

function cLog(content) {
    console.log(content)
}

if($(window).width() > 800) {
    $(document).on("mouseover", ".news__item", function (_event, _element) {

        var newsItem = document.querySelectorAll('.news__item');
        newsItem.forEach(function (element, index) {
            element.addEventListener('mouseover', function () {
                var x = this.getBoundingClientRect().left;
                var y = this.getBoundingClientRect().top;
                var width = this.getBoundingClientRect().width;
                var height = this.getBoundingClientRect().height;

                $('.item-bg').addClass('active');
                $('.news__item').removeClass('active');

                bg.style.width = width + 'px';
                bg.style.height = height + 'px';
                bg.style.transform = 'translateX(' + x + 'px ) translateY(' + y + 'px)';
            });

            element.addEventListener('mouseleave', function () {
                $('.item-bg').removeClass('active');
                $('.news__item').removeClass('active');
            });

        });

    });
}


var swiper = new Swiper('.news-slider', {
    effect: 'coverflow',
    grabCursor: true,
    loop: true,
    centeredSlides: true,
    keyboard: true,
    spaceBetween: 0,
    slidesPerView: 'auto',
    speed: 300,
    coverflowEffect: {
        rotate: 0,
        stretch: 0,
        depth: 0,
        modifier: 3,
        slideShadows: false
    },
    breakpoints: {
        480: {
            spaceBetween: 0,
            centeredSlides: true
        }
    },
    simulateTouch: true,
    navigation: {
        nextEl: '.news-slider-next',
        prevEl: '.news-slider-prev'
    },
    pagination: {
        el: '.news-slider__pagination',
        clickable: true
    },
    on: {
        init: function () {
            var activeItem = document.querySelector('.swiper-slide-active');

            var sliderItem = activeItem.querySelector('.news__item');

            $('.swiper-slide-active .news__item').addClass('active');

            var x = sliderItem.getBoundingClientRect().left;
            var y = sliderItem.getBoundingClientRect().top;
            var width = sliderItem.getBoundingClientRect().width;
            var height = sliderItem.getBoundingClientRect().height;


            $('.item-bg').addClass('active');

            bg.style.width = width + 'px';
            bg.style.height = height + 'px';
            bg.style.transform = 'translateX(' + x + 'px ) translateY(' + y + 'px)';
        }
    }
});

swiper.on('touchEnd', function () {
    $('.news__item').removeClass('active');
    $('.swiper-slide-active .news__item').addClass('active');
});

swiper.on('slideChange', function () {
    $('.news__item').removeClass('active');
});

swiper.on('slideChangeTransitionEnd', function () {
    $('.news__item').removeClass('active');
    var activeItem = document.querySelector('.swiper-slide-active');

    var sliderItem = activeItem.querySelector('.news__item');

    $('.swiper-slide-active .news__item').addClass('active');

    var x = sliderItem.getBoundingClientRect().left;
    var y = sliderItem.getBoundingClientRect().top;
    var width = sliderItem.getBoundingClientRect().width;
    var height = sliderItem.getBoundingClientRect().height;


    $('.item-bg').addClass('active');

    bg.style.width = width + 'px';
    bg.style.height = height + 'px';
    bg.style.transform = 'translateX(' + x + 'px ) translateY(' + y + 'px)';
});

Final Output:

Creating a Responsive News Card Slider with HTML, CSS, JavaScript, and Swiper.gif

Conclusion:

In conclusion, a responsive news card slider is an excellent addition to any website. It not only enhances user engagement but also presents your content in an appealing way. By following the steps outlined in this blog post, you can create a dynamic and interactive news card slider using HTML, CSS, JavaScript, and the Swiper library.

Remember that the key to success lies in a well-structured HTML layout, creative CSS styling, and effective JavaScript implementation. With the Swiper library's assistance, you can make your website stand out with an engaging news card slider. Don't hesitate to explore and customize further to match your website's unique style. Happy coding!

Code by: Muhammed Erdem

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post