How to set styles for <swiper-slide> when using injectStyles in Swiper Element (WebComponent)? – Javascript

by
Ali Hasan
cssgrid swiper.js

Quick Fix: You can adjust the styles of different Swiper Element (WebComponent) parts by adding CSS variables and styles to your stylesheet.

The Problem:

I’m utilizing the Swiper Element (WebComponent), and I’m aiming to make adjustments to the styles of individual slides. I’m using injectStyles for this purpose, but it’s only effective for :host and :host .swiper-wrapper elements, while the styling for :host .swiper-slide is not being applied. I have tried various selector combinations, including :host .slide and :host swiper-slide, but none of them seem to work. It appears that the styles aren’t being applied because the <swiper-slide> elements are slotted into the shadow element. I’m seeking a solution to style these elements without having to use multiple locations like the Swiper config and component SCSS.

The Solutions:

Solution 1: Use Custom CSS Properties

You can define custom CSS properties in your stylesheet and use them to style the <swiper-slide> elements. To do this, add the following to your stylesheet:

swiper-container {
  --swiper-slide-background-color: #ffffff;
  --swiper-slide-border-color: #000000;
  --swiper-slide-border-width: 1px;
}

swiper-slide {
  background-color: var(--swiper-slide-background-color);
  border: var(--swiper-slide-border-width) solid var(--swiper-slide-border-color);
}

This will set the background color and border of each slide to the values specified in the custom CSS properties. You can then override these values for specific slides by using the style attribute on the <swiper-slide> element. For example:

&lt;swiper-slide style="background-color: #ff0000"&gt;
  ...
&lt;/swiper-slide&gt;

This will set the background color of the specified slide to red, overriding the value set in the custom CSS property.

Q&A

How to apply styles to <swiper-slide> using injectStyles in Swiper Element (WebComponent)?

Use ::ng-deep in Angular component SCSS to style <swiper-slide> elements.

Can I style other components inside Swiper in a similar way?

Yes, use ::part() selector to style other components like pagination, navigation etc.

Where can I find examples of styling the Swiper Element (WebComponent)?

Refer to the Swiper documentation for styling examples.

Video Explanation:

The following video, titled "How to use Styles in Microsoft Word - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

In this step-by-step tutorial video, learn how and why to use Styles in Microsoft Word. With Styles, you can easily format and change the ...