Skip to content

Use 0 specificity for built-in swiper classes #8164

@cbodin

Description

@cbodin

Clear and concise description of the problem

I can override Swiper styling by adding an additional class to the container/wrapper/slide to achieve things like showing the slides outside the container.

However, when using CSS Modules with frameworks like Next.js the custom class might have the same specificity as the swiper-slide. E.g:

/* swiper.css */
.swiper-container {
  overflow: hidden;
}

/* MyComponent.module.css */
.MyComponent-module__Mo-xHa__swiperContainer {
  overflow: visible;
}

The resulting value of the overflow property is dependent on the order of the css in the document, which is not deterministic in frameworks such as Next.js if not imported in the entry file. Importing it in the entry file is not great as it will include the css on all pages, even though only 1% of users might open a page with a slider.

Suggested solution

Swiper could set the specificity of all the selectors to 0 using the :where selector.

This is baseline available since over 5 years ago.

Before:

.swiper {
  margin-left: auto;
  margin-right: auto;
  position: relative;
  overflow: hidden;
  list-style: none;
  padding: 0;
  /* Fix of Webkit flickering */
  z-index: 1;
  display: block;
}

.swiper-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 1;
  display: flex;
  transition-property: transform;
  transition-timing-function: var(--swiper-wrapper-transition-timing-function, initial);
  box-sizing: content-box;
}

After:

:where(.swiper) {
  margin-left: auto;
  margin-right: auto;
  position: relative;
  overflow: hidden;
  list-style: none;
  padding: 0;
  /* Fix of Webkit flickering */
  z-index: 1;
  display: block;
}

:where(.swiper-wrapper) {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 1;
  display: flex;
  transition-property: transform;
  transition-timing-function: var(--swiper-wrapper-transition-timing-function, initial);
  box-sizing: content-box;
}

Alternative

  • Use !important on all overriding styles.
    • This is easily missed and will force all :hover/:focus selectors to also use !important.
  • Add an extra wrapper with a css class to increase specificity of custom selectors.
    • This adds unnecessary DOM-elements and styles.

Additional context

No response

Validations

  • Follow our Code of Conduct
  • Read the docs.
  • Check that there isn't already an issue that request the same feature to avoid creating a duplicate.

Would you like to open a PR for this feature?

  • I'm willing to open a PR

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions